<?php

namespace App\Console\Commands;

use App\Campaigns\Targeting\LocationCatalogImporter;
use App\Models\Location;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use JsonException;
use RuntimeException;
use Throwable;

#[Signature('locations:snapshot {action : export or import} {path : JSON Lines snapshot path} {--force : Replace an existing export file}')]
#[Description('Export or import platform location candidates without database row IDs')]
class LocationCatalogSnapshot extends Command
{
    public function handle(LocationCatalogImporter $importer): int
    {
        $action = (string) $this->argument('action');
        $path = (string) $this->argument('path');

        if (! in_array($action, ['export', 'import'], true)) {
            $this->error('Choose export or import.');

            return self::FAILURE;
        }

        try {
            $count = $action === 'export' ? $this->export($path) : $this->import($path, $importer);
        } catch (Throwable $exception) {
            $this->error($exception->getMessage());

            return self::FAILURE;
        }

        $this->info(($action === 'export' ? 'Exported ' : 'Processed ').$count.' location candidates.');

        return self::SUCCESS;
    }

    private function export(string $path): int
    {
        if (is_file($path) && ! $this->option('force')) {
            throw new RuntimeException('The snapshot already exists. Use --force to replace it.');
        }

        if (! is_dir(dirname($path)) || ! is_writable(dirname($path))) {
            throw new RuntimeException('The snapshot directory must exist and be writable.');
        }

        $temporaryPath = tempnam(dirname($path), 'locations-');
        if ($temporaryPath === false) {
            throw new RuntimeException('The snapshot directory must exist and be writable.');
        }

        $stream = fopen($temporaryPath, 'wb');
        if ($stream === false) {
            unlink($temporaryPath);
            throw new RuntimeException('Could not open the snapshot for writing.');
        }

        try {
            $this->writeLine($stream, ['format' => 'arb-location-catalog', 'version' => 2]);
            $count = 0;
            $rows = DB::table('platform_locations')
                ->join('locations', 'locations.id', '=', 'platform_locations.location_id')
                ->whereIn('locations.type', ['city', 'region', 'dma'])
                ->whereIn('platform_locations.platform', ['meta', 'google', 'linkedin'])
                ->whereIn('platform_locations.status', ['verified', 'unverified'])
                ->select([
                    'platform_locations.platform', 'platform_locations.external_id',
                    'locations.type as kind', 'locations.name',
                    'platform_locations.provider_name as label', 'locations.country_code',
                    'platform_locations.parent_external_id', 'platform_locations.catalog_priority',
                ])
                ->orderBy('platform_locations.id')->cursor();

            foreach ($rows as $row) {
                $this->writeLine($stream, (array) $row);
                $count++;
            }
        } catch (Throwable $exception) {
            fclose($stream);
            unlink($temporaryPath);

            throw $exception;
        }

        fclose($stream);
        if (! rename($temporaryPath, $path)) {
            unlink($temporaryPath);
            throw new RuntimeException('Could not finish writing the snapshot.');
        }

        return $count;
    }

    private function import(string $path, LocationCatalogImporter $importer): int
    {
        if (! is_file($path) || ! is_readable($path)) {
            throw new RuntimeException('The snapshot file is not readable.');
        }

        $count = 0;
        $this->line('Validating snapshot...');
        foreach ($this->candidates($path) as $candidate) {
            $count++;
        }

        $this->line('Importing '.$count.' location candidates...');
        $bar = $this->output->createProgressBar($count);
        $bar->start();

        $chunk = [];
        foreach ($this->candidates($path) as $candidate) {
            $chunk[] = $candidate;
            if (count($chunk) === 250) {
                $importer->store($chunk);
                $bar->advance(count($chunk));
                $chunk = [];
            }
        }

        if ($chunk !== []) {
            $importer->store($chunk);
            $bar->advance(count($chunk));
        }

        $bar->finish();
        $this->newLine();

        return $count;
    }

    /**
     * @return \Generator<int, array{platform: string, external_id: string, kind: string, name: string, label: string, country_code: string, parent_external_id: string|null, catalog_priority: int}>
     */
    private function candidates(string $path): \Generator
    {
        $stream = fopen($path, 'rb');
        if ($stream === false) {
            throw new RuntimeException('Could not open the snapshot for reading.');
        }

        try {
            $header = json_decode((string) fgets($stream), true, 512, JSON_THROW_ON_ERROR);
            if (! in_array($header, [
                ['format' => 'arb-location-catalog', 'version' => 1],
                ['format' => 'arb-location-catalog', 'version' => 2],
            ], true)) {
                throw new RuntimeException('The snapshot format is not supported.');
            }

            $countries = [];
            $lineNumber = 1;
            while (($line = fgets($stream)) !== false) {
                $lineNumber++;
                $candidate = json_decode($line, true, 512, JSON_THROW_ON_ERROR);
                if (! is_array($candidate)
                    || ! in_array($candidate['platform'] ?? null, ['meta', 'google', 'linkedin'], true)
                    || ! in_array($candidate['kind'] ?? null, ['city', 'region', 'dma'], true)
                    || ! is_string($candidate['external_id'] ?? null) || blank($candidate['external_id'])
                    || ! is_string($candidate['name'] ?? null) || blank($candidate['name'])
                    || ! is_string($candidate['label'] ?? null) || blank($candidate['label'])
                    || ! is_string($candidate['country_code'] ?? null)
                    || ! preg_match('/^[A-Z]{2}$/D', $candidate['country_code'])
                    || ! is_null($candidate['parent_external_id'] ?? null) && ! is_string($candidate['parent_external_id'])
                    || $header['version'] === 2 && ! in_array($candidate['catalog_priority'] ?? null, [0, 1], true)) {
                    throw new RuntimeException('Invalid location candidate on line '.$lineNumber.'.');
                }

                $country = $candidate['country_code'];
                if (! isset($countries[$country])) {
                    if (! Location::query()->where('type', 'country')->where('iso_code', $country)->exists()) {
                        throw new RuntimeException('Seed the '.$country.' country before importing the snapshot.');
                    }
                    $countries[$country] = true;
                }

                $candidate['catalog_priority'] = $header['version'] === 2 ? $candidate['catalog_priority'] : 0;

                yield $candidate;
            }
        } catch (JsonException $exception) {
            throw new RuntimeException('The snapshot contains invalid JSON.', previous: $exception);
        } finally {
            fclose($stream);
        }
    }

    /** @param resource $stream */
    private function writeLine($stream, array $value): void
    {
        $line = json_encode($value, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE)."\n";
        if (fwrite($stream, $line) !== strlen($line)) {
            throw new RuntimeException('Could not write the snapshot.');
        }
    }
}
