<?php

namespace App\Console\Commands;

use App\Campaigns\Targeting\LocationCatalogImporter;
use App\Campaigns\Targeting\LocationDiscovery;
use App\Models\GoogleAdsConnection;
use App\Models\Location;
use App\Models\PlatformConnection;
use App\Services\GoogleAdsService;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Throwable;

#[Signature('locations:import {platform : meta, google, or linkedin} {kind : city, region, or dma} {country : Two-letter country code} {--account= : Override the connected ad account ID} {--all : Import all Google Ads geo targets of this kind and country} {--query=* : Search term; repeat for more terms} {--terms-file= : UTF-8 file with one search term per line} {--from-database : Search names already known on other platforms} {--offset=0 : Starting name offset for --from-database} {--limit=500 : Names to process from the database, 1 to 500} {--pages=1 : Meta pages per term, up to 4}')]
#[Description('Fetch city, region, or DMA candidates from an ad platform into the location catalog')]
class ImportLocationCatalog extends Command
{
    public function handle(LocationDiscovery $discovery, LocationCatalogImporter $importer, GoogleAdsService $google): int
    {
        $platform = strtolower((string) $this->argument('platform'));
        $kind = strtolower((string) $this->argument('kind'));
        $country = strtoupper((string) $this->argument('country'));
        $account = trim((string) $this->option('account'));
        $pages = (int) $this->option('pages');
        $offset = (int) $this->option('offset');
        $limit = (int) $this->option('limit');

        if (! in_array($platform, ['meta', 'google', 'linkedin'], true)
            || ! in_array($kind, ['city', 'region', 'dma'], true)
            || ($platform === 'linkedin' && $kind !== 'dma')
            || ($kind === 'dma' && $country !== 'US')
            || ! preg_match('/^[A-Z]{2}$/D', $country)
            || $pages < 1 || $pages > 4 || $offset < 0 || $limit < 1 || $limit > 500
            || ($platform !== 'meta' && $pages !== 1)
            || ($this->option('all') && $platform !== 'google')) {
            $this->error('Provide a supported platform, kind, country, and page count.');

            return self::FAILURE;
        }

        if (! Location::query()->where('type', 'country')->where('iso_code', $country)->exists()) {
            $this->error('Seed the country catalog before importing places.');

            return self::FAILURE;
        }

        $googleConnection = $platform === 'google' ? GoogleAdsConnection::shared() : null;
        $account = $account !== '' ? $account : (string) match ($platform) {
            'google' => $googleConnection?->customer_id,
            'meta' => PlatformConnection::sharedAccountId('meta', config('services.meta.ad_account_id')),
            'linkedin' => PlatformConnection::sharedAccountId('linkedin', config('platforms.linkedin.ad_account_id')),
        };

        if ($account === '') {
            $this->error('No connected '.$platform.' ad account is configured. Connect an account or pass --account.');

            return self::FAILURE;
        }

        if ($platform === 'google' && ($googleConnection === null
            || preg_replace('/\D/', '', $account) !== preg_replace('/\D/', '', (string) $googleConnection->customer_id))) {
            $this->error('The Google account must match the connected Google Ads customer.');

            return self::FAILURE;
        }

        $priorityTerms = array_map(trim(...), (array) $this->option('query'));
        $terms = $priorityTerms;
        $file = $this->option('terms-file');
        $onlyDatabaseTerms = $this->option('from-database') && $terms === [] && blank($file);

        if (is_string($file) && $file !== '') {
            if (! is_file($file) || ! is_readable($file)) {
                $this->error('The terms file is not readable.');

                return self::FAILURE;
            }

            $terms = array_merge($terms, file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []);
        }

        $databaseTerms = [];
        if ($this->option('from-database')) {
            $databaseTerms = Location::query()
                ->where('type', $kind)->where('country_code', $country)
                ->where('source', '!=', $platform)
                ->distinct()->orderBy('name')->offset($offset)->limit($limit)->pluck('name')->all();
            $terms = array_merge($terms, $databaseTerms);
        }

        $terms = array_values(array_unique(array_filter(array_map(
            fn (mixed $term): string => trim((string) $term), $terms,
        ), fn (string $term): bool => mb_strlen($term) >= 2 && mb_strlen($term) <= 80)));

        if (($terms === [] && ! $this->option('all')) || count($terms) > 500) {
            if ($onlyDatabaseTerms && $databaseTerms === []) {
                $this->info('No more database names to import.');

                return self::SUCCESS;
            }
            $this->error('Provide 1 to 500 search terms with --query, --terms-file, or --from-database.');

            return self::FAILURE;
        }

        $stored = 0;
        $currentSource = 'Google catalog';
        $processed = 0;

        try {
            if ($this->option('all')) {
                $stored += $importer->store($google->geoTargetCatalog($googleConnection, $kind, $country, $account));
            }

            foreach ($terms as $term) {
                $currentSource = $term;
                for ($page = 1; $page <= $pages; $page++) {
                    $matches = $discovery->search($platform, $kind, $country, $term, $account, $page);
                    $stored += $importer->store($matches, in_array($term, $priorityTerms, true) ? $term : null);

                    if ($matches === []) {
                        break;
                    }
                }
                $processed++;
            }
        } catch (Throwable $exception) {
            $this->error('Import stopped at '.$currentSource.': '.$exception->getMessage());
            if ($onlyDatabaseTerms) {
                $this->warn('Resume with --offset='.($offset + $processed).' --limit='.$limit.'.');
            }

            return self::FAILURE;
        }

        $this->info('Stored '.$stored.' provider candidates from '.count($terms).' search terms'.($this->option('all') ? ' and the Google catalog' : '').'.');
        if ($onlyDatabaseTerms) {
            $this->info(count($databaseTerms) < $limit
                ? 'All database names have been processed.'
                : 'Next batch: --offset='.($offset + $processed).' --limit='.$limit.'.');
        }

        return self::SUCCESS;
    }
}
