<?php

namespace App\Campaigns\Targeting;

use App\Campaigns\PendingChanges;
use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
use App\Models\PlatformLocation;
use App\Services\GoogleAdsService;
use App\Services\Meta\Meta;
use RuntimeException;

class PublishedLocationReadback
{
    public function __construct(
        private readonly TargetingSelections $selections,
        private readonly PendingChanges $pending,
        private readonly Meta $meta,
        private readonly GoogleAdsService $google,
    ) {}

    /** @return array{status: string, platform: string, expected: array<string, list<string>>, actual: array<string, list<string>>} */
    public function inspect(Campaign $campaign): array
    {
        if (! $campaign->isPublished() || ! in_array($campaign->platform, ['meta', 'google'], true)) {
            throw new RuntimeException('Select a published Meta or Google campaign to check its locations.');
        }

        $baseline = (array) ($campaign->published_state ?? []);

        if (! array_key_exists('locations', $baseline) || ! array_key_exists('targeting_locations', $baseline)) {
            throw new RuntimeException('This campaign has no complete published location baseline. Reopen it before comparing locations.');
        }

        $publishedCountries = data_get($baseline, 'locations.countries');

        if (! is_array($publishedCountries)) {
            throw new RuntimeException('This campaign has no saved published country selection to compare. Reopen it before editing locations.');
        }

        $currentCountries = $this->selections->countries($campaign);
        sort($publishedCountries);
        sort($currentCountries);

        if ($publishedCountries !== $currentCountries) {
            throw new RuntimeException('Local country targeting changed after publication. Review it before comparing provider state.');
        }

        $localDrift = array_filter($this->pending->requiringRebuild($campaign),
            fn (string $problem): bool => str_contains($problem, 'location targeting changed')
                || str_contains($problem, 'city or region targeting changed')
                || str_contains($problem, 'location presence preference changed'),
        );

        if ($localDrift !== []) {
            throw new RuntimeException('Local location targeting changed after publication. Review those changes before comparing provider state.');
        }

        [$expected, $actual] = $campaign->platform === 'meta'
            ? $this->metaLocations($campaign)
            : $this->googleLocations($campaign);

        return [
            'status' => $expected === $actual ? 'matches' : 'drift',
            'platform' => $campaign->platform,
            'expected' => $expected,
            'actual' => $actual,
        ];
    }

    /** @return array{array<string, list<string>>, array<string, list<string>>} */
    private function metaLocations(Campaign $campaign): array
    {
        if (filled($campaign->locations['meta_geo_locations'] ?? null)) {
            throw new RuntimeException('Imported Meta geography includes criteria this comparison cannot verify yet.');
        }

        $expected = $this->normaliseMeta($this->selections->metaGeoLocations($campaign));
        $ids = (array) ($campaign->external_ids ?? []);

        if (blank($ids['adset_id'] ?? null) || filled($ids['other_adset_ids'] ?? null)) {
            throw new RuntimeException('A single recorded Meta ad set is required to compare live locations.');
        }

        $actualAccount = $this->meta->campaignAccountId((string) $campaign->external_campaign_id);
        if ('act_'.preg_replace('/^act_/', '', (string) $actualAccount) !== (string) $campaign->ad_account_id) {
            throw new RuntimeException('This Meta campaign belongs to a different ad account.');
        }

        $adSets = $this->meta->adSets((string) $campaign->external_campaign_id, $campaign->ad_account_id, fresh: true);

        if (count($adSets) !== 1 || (string) ($adSets[0]['id'] ?? '') !== (string) $ids['adset_id']
            || ! is_array(data_get($adSets[0], 'targeting.geo_locations'))) {
            throw new RuntimeException('Meta returned different ad sets or omitted geographic targeting. Refresh the campaign before editing locations.');
        }

        return [$expected, $this->normaliseMeta(data_get($adSets[0], 'targeting.geo_locations'))];
    }

    /** @param array<string, mixed> $geo
     * @return array{countries: list<string>, cities: list<string>, regions: list<string>, zips?: list<string>, geo_markets: list<string>}
     */
    public function normaliseMeta(array $geo): array
    {
        if (array_key_exists('location_types', $geo)) {
            $locationTypes = $geo['location_types'];

            if (! is_array($locationTypes) || ! array_is_list($locationTypes)) {
                throw new RuntimeException('Meta returned an unreadable location-presence setting.');
            }

            sort($locationTypes);

            if ($locationTypes !== ['frequently_in', 'home', 'recent']) {
                throw new RuntimeException('Meta returned a different location-presence setting. Review it before editing locations.');
            }

            unset($geo['location_types']);
        }

        if (array_diff(array_keys($geo), ['countries', 'cities', 'regions', 'zips', 'geo_markets']) !== []) {
            throw new RuntimeException('Meta returned additional geographic controls that cannot be compared safely yet.');
        }

        $result = ['countries' => [], 'cities' => [], 'regions' => [], 'geo_markets' => []];
        // Only present when postal codes are targeted, so existing comparisons keep their shape.
        $kinds = array_key_exists('zips', $geo) ? ['countries', 'cities', 'regions', 'zips', 'geo_markets'] : array_keys($result);

        foreach ($kinds as $kind) {
            $entries = $geo[$kind] ?? [];

            if (! is_array($entries)) {
                throw new RuntimeException('Meta returned unreadable geographic targeting.');
            }

            foreach ($entries as $entry) {
                if ($kind !== 'countries' && (! is_array($entry)
                    || array_key_exists('radius', $entry))) {
                    throw new RuntimeException('Meta returned city or region radius targeting that cannot be compared safely yet.');
                }

                $value = $kind === 'countries' ? $entry : ($entry['key'] ?? null);

                if (! is_scalar($value) || (string) $value === '') {
                    throw new RuntimeException('Meta returned a geographic criterion without an identifier.');
                }

                if ($kind === 'geo_markets' && ! preg_match('/^COMSCORE_MARKET:[0-9]+$/D', (string) $value)) {
                    throw new RuntimeException('Meta returned an unrecognised market key.');
                }

                $result[$kind][] = (string) $value;
            }

            $result[$kind] = array_values(array_unique($result[$kind]));
            sort($result[$kind]);
        }

        return $result;
    }

    /** @return array{array<string, list<string>>, array<string, list<string>>} */
    private function googleLocations(Campaign $campaign): array
    {
        if (filled($campaign->locations['google_location_criteria'] ?? null)
            || filled($campaign->locations['google_proximity_criteria'] ?? null)) {
            throw new RuntimeException('Imported Google geography includes criteria this comparison cannot verify yet.');
        }

        $connection = GoogleAdsConnection::shared()
            ?? throw new RuntimeException(GoogleAdsConnection::missingReason());

        // Adopted rather than refused. This compared the configured customer
        // against the campaign's and threw, which was safe while one account
        // was permitted and became a contradiction the moment the flow started
        // asking which of the manager's children to buy on: refusing the answer
        // to our own question. The allow list still gates the account inside
        // CallLogger, which is the check that matters.
        $connection = $connection->onCustomer((string) $campaign->ad_account_id);

        if (isset($campaign->targetingSet()->first()?->options['google_presence'])
            && $this->google->readCampaignGeoPresence($connection, (string) $campaign->external_campaign_id, fresh: true)
                !== $this->selections->googlePresenceMode($campaign)) {
            throw new RuntimeException('Google location-presence setting differs from the saved selection. Review it before editing locations.');
        }

        $targets = $this->selections->googleGeoTargets($campaign);
        $countryIds = [];

        foreach ($targets['countries'] as $code) {
            $mappings = PlatformLocation::query()->where('platform', 'google')
                ->where('status', 'verified')->whereNotNull('verified_at')
                ->where('verified_at', '>=', now()->subDays(30))
                ->whereHas('location', fn ($query) => $query->where('type', 'country')->where('iso_code', $code))
                ->pluck('external_id')->all();

            if (count($mappings) !== 1) {
                throw new RuntimeException('The saved Google country mapping is missing or ambiguous. Verify it before comparing live locations.');
            }

            $countryIds[] = $mappings[0];
        }

        $expectedProximities = $targets['proximity_targets'] ?? [];
        $expected = $this->normaliseGoogleIds(
            [...$countryIds, ...$targets['geo_targets']], $targets['excluded_geo_targets'] ?? [], $expectedProximities,
        );
        $criteria = $expectedProximities === []
            ? $this->google->readCampaignLocationCriteria($connection, (string) $campaign->external_campaign_id, includeStatus: true, fresh: true)
            : $this->google->readCampaignLocationCriteria(
                $connection, (string) $campaign->external_campaign_id, includeStatus: true, allowProximity: true, fresh: true,
            );

        foreach ($criteria as $criterion) {
            if (($criterion['status'] ?? null) !== 'ENABLED'
                || ! in_array($criterion['target_type'], ['Country', 'City', 'State', 'Province', 'Region', 'Territory', 'Postal Code', 'DMA Region'], true)) {
                throw new RuntimeException('Google returned paused or unsupported geography. Preserve it and review the campaign before editing locations.');
            }
        }

        $included = array_column(array_values(array_filter($criteria, fn (array $criterion): bool => ! $criterion['negative'])), 'geo_target');
        $excluded = array_column(array_values(array_filter($criteria, fn (array $criterion): bool => $criterion['negative'])), 'geo_target');
        $proximities = $expectedProximities === [] ? []
            : $this->google->readCampaignProximityCriteria($connection, (string) $campaign->external_campaign_id, fresh: true);

        foreach ($proximities as $proximity) {
            if ($proximity['negative'] || $proximity['status'] !== 'ENABLED') {
                throw new RuntimeException('Google returned unsupported or paused proximity targeting. Review it before editing locations.');
            }
        }

        return [$expected, $this->normaliseGoogleIds($included, $excluded, $proximities)];
    }

    /** @param list<string> $ids
     * @param  list<string>  $excludedIds
     * @param  list<array{latitude: float, longitude: float, radius: float, radius_unit: string}>  $proximities
     * @return array{geo_targets: list<string>, excluded_geo_targets?: list<string>, proximity_targets?: list<string>}
     */
    private function normaliseGoogleIds(array $ids, array $excludedIds = [], array $proximities = []): array
    {
        if (count($ids) !== count(array_unique($ids))
            || count($excludedIds) !== count(array_unique($excludedIds))
            || array_intersect($ids, $excludedIds) !== []) {
            throw new RuntimeException('Duplicate Google geographic criteria need review before comparing locations.');
        }

        sort($ids);
        sort($excludedIds);
        $radiusKeys = array_map(fn (array $proximity): string => sprintf('%.6F,%.6F:%.2F:%s',
            $proximity['latitude'], $proximity['longitude'], $proximity['radius'], $proximity['radius_unit'],
        ), $proximities);

        if (count($radiusKeys) !== count(array_unique($radiusKeys))) {
            throw new RuntimeException('Duplicate Google proximity criteria need review before comparing locations.');
        }

        sort($radiusKeys);

        return [
            'geo_targets' => $ids,
            ...($excludedIds === [] ? [] : ['excluded_geo_targets' => $excludedIds]),
            ...($radiusKeys === [] ? [] : ['proximity_targets' => $radiusKeys]),
        ];
    }
}
