<?php

declare(strict_types=1);

namespace BadamSoft\WooProductExporter\Helpers;

class RunLogFormatter {
    /**
     * @param array<string, mixed> $context
     */
    public static function formatSuccessLog( array $context ): string {
        $rows       = isset( $context['rows'] ) ? max( 0, (int) $context['rows'] ) : 0;
        $file       = self::first_non_empty( $context['file_url'] ?? '', $context['file_path'] ?? '' );
        $images_zip = self::first_non_empty( $context['images_zip_url'] ?? '', $context['images_zip_path'] ?? '' );
        $format     = isset( $context['file_format'] ) ? strtoupper( (string) $context['file_format'] ) : '';

        $parts   = [];
        $parts[] = sprintf(
            /* translators: %s: number of rows exported */
            __( 'Export finished successfully: %s rows', 'badamsoft-product-exporter-for-woocommerce' ),
            \number_format_i18n( $rows )
        );

        if ( $format ) {
            $parts[] = sprintf(
                /* translators: %s: export format */
                __( 'Format: %s', 'badamsoft-product-exporter-for-woocommerce' ),
                $format
            );
        }

        if ( $file ) {
            $parts[] = sprintf(
                /* translators: %s: export file name */
                __( 'File: %s', 'badamsoft-product-exporter-for-woocommerce' ),
                self::extract_file_name( $file )
            );
        }

        if ( $images_zip ) {
            $parts[] = sprintf(
                /* translators: %s: images ZIP file name */
                __( 'Images ZIP: %s', 'badamsoft-product-exporter-for-woocommerce' ),
                self::extract_file_name( $images_zip )
            );
        }

        return implode( ' · ', array_filter( $parts ) );
    }

    /**
     * @param array<string, mixed> $context
     */
    public static function formatFailureLog( array $context ): string {
        $rows        = isset( $context['rows'] ) ? max( 0, (int) $context['rows'] ) : 0;
        $error       = isset( $context['error'] ) ? trim( (string) $context['error'] ) : '';
        $failed_rows = [];

        if ( isset( $context['failed_rows'] ) && is_array( $context['failed_rows'] ) ) {
            $failed_rows = array_values(
                array_filter(
                    array_unique(
                        array_map(
                            static function ( $value ): int {
                                return (int) $value;
                            },
                            $context['failed_rows']
                        )
                    ),
                    static function ( int $value ): bool {
                        return $value > 0;
                    }
                )
            );
        }

        $parts   = [];
        $parts[] = $rows > 0
            ? sprintf(
                /* translators: %s: number of rows exported before failure */
                __( 'Export failed after %s rows.', 'badamsoft-product-exporter-for-woocommerce' ),
                \number_format_i18n( $rows )
            )
            : __( 'Export failed before any rows were written.', 'badamsoft-product-exporter-for-woocommerce' );

        if ( ! empty( $failed_rows ) ) {
            $preview = array_slice( $failed_rows, 0, 10 );
            $suffix  = count( $failed_rows ) > 10 ? '…' : '';
            $parts[] = sprintf(
                /* translators: %s: list of row numbers */
                __( 'Problematic rows: %s', 'badamsoft-product-exporter-for-woocommerce' ),
                implode( ', ', $preview ) . $suffix
            );
        }

        if ( $error !== '' ) {
            $parts[] = sprintf(
                /* translators: %s: error message */
                __( 'Error: %s', 'badamsoft-product-exporter-for-woocommerce' ),
                $error
            );
        }

        return implode( ' ', array_filter( $parts ) );
    }

    private static function extract_file_name( string $value ): string {
        $trimmed = trim( $value );

        if ( '' === $trimmed ) {
            return '';
        }

        $clean = preg_split( '/[?#]/', $trimmed )[0] ?? $trimmed;
        $name  = basename( $clean );

        return $name ?: $trimmed;
    }

    private static function first_non_empty( string ...$candidates ): string {
        foreach ( $candidates as $candidate ) {
            $trimmed = trim( $candidate );

            if ( '' !== $trimmed ) {
                return $trimmed;
            }
        }

        return '';
    }
}
