<?php

declare(strict_types=1);

namespace PortalPeople\palletforce\commands;

use PortalPeople\palletforce\services\PalletforcePdfRateParser;
use PortalPeople\shippingcosts\components\PriceImporter;
use PortalPeople\shippingcosts\services\PdfToMarkdownService;
use yii\console\Controller;
use yii\console\ExitCode;

/** Safely previews or explicitly imports the bundled Palletforce sample card. */
final class RateCardController extends Controller
{
    public string $file = '';
    public bool $import = false;
    public int $limit = 10;

    public function options($actionID): array
    {
        return ['file', 'import', 'limit'];
    }

    public function actionRun(): int
    {
        $path = $this->file !== ''
            ? $this->file
            : dirname(__DIR__) . '/data/AHS Discounted 2026 Rate Card.pdf';
        if (!is_file($path)) {
            $this->stderr("Sample rate card not found: {$path}\n");
            return ExitCode::DATAERR;
        }

        $markdown = (new PdfToMarkdownService())->convert($path);
        $rows = (new PalletforcePdfRateParser())->parse($markdown, 'Palletforce');
        $validRows = array_values(array_filter(
            $rows,
            static fn (array $row): bool => empty($row['requires_review'])
        ));
        $reviewRows = count($rows) - count($validRows);

        $this->stdout("Palletforce sample: {$path}\n");
        $this->stdout('Parsed rows: ' . count($rows) . "\n");
        $this->stdout("Review rows: {$reviewRows}\n");
        foreach (array_slice($rows, 0, max(0, $this->limit)) as $row) {
            $this->stdout(sprintf(
                "- band=%s service=%s postcode=%s%s\n",
                $row['Band'] ?? '',
                $row['Service'] ?? '',
                $row['PostCode'] ?? '',
                !empty($row['requires_review']) ? ' [review]' : ''
            ));
        }

        if (!$this->import) {
            $this->stdout("Preview only. Re-run with --import=1 to persist valid rows.\n");
            return ExitCode::OK;
        }

        if ($validRows === []) {
            $this->stderr("No valid rows are available for import.\n");
            return ExitCode::DATAERR;
        }

        $result = (new PriceImporter($this->assignments($validRows[0])))->import($validRows);
        $this->stdout(json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n");
        return ExitCode::OK;
    }

    /** @param array<string, mixed> $row @return array<string, string> */
    private function assignments(array $row): array
    {
        $assignments = [];
        foreach (array_keys($row) as $header) {
            $assignments[$header] = match ($header) {
                'Provider' => 'haulierid',
                'Service' => 'type',
                'PostCode' => 'postcodes',
                'Qtr', 'Half', 'Full', '2', '3', '4', '5', '5+ per pallet' => 'price',
                default => 'ignore',
            };
        }

        return $assignments;
    }
}
