#!/usr/bin/env php
<?php

declare(strict_types=1);

use FeedManager\Application\PersistedFeedExportService;
use FeedManager\Feeds\GoogleMerchant\GoogleMerchantRssWriter;
use FeedManager\Repositories\VariantStateRepository;
use FeedManager\Support\DotenvLoader;
use FeedManager\Support\JsonFileWriter;
use FeedManager\Support\PdoFactory;

require_once __DIR__ . '/../bootstrap.php';

$clientName = $argv[1] ?? null;

if (!is_string($clientName) || trim($clientName) === '') {
    fwrite(STDERR, "Usage: php bin/export-feed <client-name>\n");
    exit(1);
}

try {
    DotenvLoader::load(__DIR__ . '/../.env');
    $pdo = PdoFactory::fromEnv();

    $configPath = __DIR__ . '/../clients/' . $clientName . '/config.php';
    if (!is_file($configPath)) {
        throw new RuntimeException(sprintf('Client config not found: %s', $configPath));
    }

    /** @var array<string, mixed> $config */
    $config = require $configPath;
    $feedConfig = $config['feed'] ?? null;
    if (!is_array($feedConfig)) {
        throw new RuntimeException('Client config missing feed section.');
    }

    $outputPath = (string) ($feedConfig['output_path'] ?? '');
    if ($outputPath === '') {
        throw new RuntimeException('Feed output_path is missing in client config.');
    }

    $reportOutputPath = (string) ($feedConfig['report_output_path'] ?? deriveReportOutputPath($outputPath));

    $service = new PersistedFeedExportService(
        variantStates: new VariantStateRepository($pdo),
        writer: new GoogleMerchantRssWriter(),
    );

    $result = $service->export(
        client: $clientName,
        outputPath: $outputPath,
        channel: [
            'title' => (string) ($feedConfig['title'] ?? 'Google Merchant Feed'),
            'link' => (string) ($feedConfig['link'] ?? 'https://example.com'),
            'description' => (string) ($feedConfig['description'] ?? 'Feed export'),
        ],
    );

    $reportPayload = [
        'schema_version' => '1.0',
        'generated_at_utc' => gmdate('c'),
        'client' => $clientName,
        'output' => [
            'xml_path' => $result['output_path'],
            'xml_size_bytes' => is_file((string) $result['output_path']) ? filesize((string) $result['output_path']) : null,
            'report_path' => $reportOutputPath,
        ],
        'counts' => [
            'persisted_rows' => $result['source_rows_count'],
            'items_exported' => $result['exported_count'],
            'items_skipped' => $result['skipped_count'],
            'identifier_exists_no' => $result['quality']['identifier_exists_no_count'],
            'with_gtin' => $result['quality']['with_gtin_count'],
            'with_mpn' => $result['quality']['with_mpn_count'],
        ],
        'validation' => [
            'missing_required_fields' => $result['quality']['missing_required_fields'],
            'invalid_availability_count' => $result['quality']['invalid_availability_count'],
            'invalid_price_count' => $result['quality']['invalid_price_count'],
        ],
        'status' => $result['quality']['status'],
        'warnings' => $result['quality']['warnings'],
        'skipped_examples' => $result['skipped_examples'],
    ];

    (new JsonFileWriter())->write($reportOutputPath, $reportPayload);

    fwrite(STDOUT, sprintf(
        "Exported %d items from persisted enriched state to %s (skipped %d)\n",
        (int) $result['exported_count'],
        (string) $result['output_path'],
        (int) $result['skipped_count']
    ));
    fwrite(STDOUT, sprintf("Wrote report to %s\n", $reportOutputPath));

    exit(0);
} catch (Throwable $e) {
    fwrite(STDERR, sprintf("Feed export failed: %s\n", $e->getMessage()));
    exit(1);
}

function deriveReportOutputPath(string $xmlOutputPath): string
{
    if (str_ends_with(strtolower($xmlOutputPath), '.xml')) {
        return substr($xmlOutputPath, 0, -4) . '-report.json';
    }

    return $xmlOutputPath . '-report.json';
}
