<?php

namespace Tests\Feature;

use App\Agent\Answers;
use App\Agent\Choices;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Targeting\LocationDiscovery;
use App\Campaigns\Targeting\LocationListResolver;
use App\Campaigns\Targeting\PublishedLocationReadback;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Campaign;
use App\Models\Location;
use App\Models\PlatformLocation;
use App\Models\User;
use App\Services\Meta\MetaException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request;
use Mockery;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

/**
 * Advanced targeting: pasted lists of places, reviewed, then saved together.
 */
class AdvancedLocationTargetingTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    private function campaign(string $platform = 'meta'): Campaign
    {
        $user = User::factory()->create();
        $this->actingAs($user);
        $this->seedVerifiedCountries();

        $campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'List draft',
            'platform' => $platform,
            'status' => 'draft',
            'ad_account_id' => $platform === 'meta' ? 'act_123' : '1234567890',
            'locations' => ['countries' => ['US']],
            'placements' => $platform === 'meta' ? ['facebook'] : [],
        ]);

        $workspace = app(Workspace::class);
        $workspace->bindTo('location-list-chat');
        $workspace->focusOn($campaign);

        return $campaign;
    }

    private function tool(array $arguments = []): array
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'campaign__target_location_list');

        return json_decode((string) $tool->handle(new Request($arguments)), true);
    }

    /** @return array{platform: string, external_id: string, kind: string, name: string, label: string, country_code: string, parent_external_id: null} */
    private function candidate(string $kind, string $id, string $name, string $label): array
    {
        return ['platform' => 'meta', 'external_id' => $id, 'kind' => $kind, 'name' => $name,
            'label' => $label, 'country_code' => 'US', 'parent_external_id' => null];
    }

    private function mapping(string $kind, string $id, string $name, string $label, string $platform = 'meta'): PlatformLocation
    {
        $location = Location::factory()->create(['type' => $kind, 'name' => $name, 'country_code' => 'US', 'iso_code' => null,
            'source' => $platform, 'source_key' => $id]);

        return PlatformLocation::factory()->create(['location_id' => $location->id, 'platform' => $platform,
            'external_id' => $id, 'provider_name' => $label]);
    }

    /** Austin and 94107 match once; Springfield matches twice; Atlantis matches nothing. */
    private function fakeDiscovery(): MockInterface
    {
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->andReturnUsing(fn (string $platform, string $kind, string $country, string $term): array => match ($term) {
            'Austin' => [$this->candidate('city', '2357536', 'Austin', 'Austin, Texas, US')],
            'Springfield' => [
                $this->candidate('city', '2493001', 'Springfield', 'Springfield, Illinois, US'),
                $this->candidate('city', '2493002', 'Springfield', 'Springfield, Missouri, US'),
            ],
            '94107' => [$this->candidate('postal', 'US:94107', '94107', '94107, San Francisco, California, US')],
            default => [],
        });
        $this->app->instance(LocationDiscovery::class, $discovery);

        return $discovery;
    }

    public function test_with_no_lists_it_offers_the_form_with_postal_codes(): void
    {
        $this->campaign();

        $this->assertTrue($this->tool()['ok']);

        $form = app(Choices::class)->all()[0];
        $this->assertSame('location_list', $form['field']);
        $this->assertSame(['region', 'city', 'dma', 'postal'], $form['location_list']['kinds']['US']);
    }

    public function test_a_list_is_reviewed_before_anything_is_saved(): void
    {
        $campaign = $this->campaign();
        $this->fakeDiscovery();

        $result = $this->tool(['cities' => ['Austin', 'Springfield', 'Atlantis'], 'postal_codes' => ['94107']]);

        $this->assertSame(['matched' => 2, 'ambiguous' => 1, 'missing' => 1], $result['summary']);
        $this->assertSame(['Atlantis'], $result['missing']);
        $review = app(Choices::class)->all()[0];
        $this->assertSame('location_list_review', $review['field']);
        $this->assertTrue($review['multiple']);
        $this->assertSame([], app(TargetingSelections::class)->reviewedCampaignPlaces($campaign->fresh()));
    }

    public function test_a_lone_result_that_only_adds_detail_counts_as_a_match(): void
    {
        $this->campaign();
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->andReturn([$this->candidate('dma', 'COMSCORE_MARKET:501', 'New York, NY', 'New York, NY, US')]);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $this->assertSame(['matched' => 1], $this->tool(['dmas' => ['New York']])['summary']);
    }

    public function test_a_qualifier_after_the_comma_settles_an_ambiguous_city(): void
    {
        $this->campaign();
        $this->fakeDiscovery();

        $result = $this->tool(['cities' => ['Springfield, Missouri']]);

        $this->assertSame(['matched' => 1], $result['summary']);
        $this->assertSame('city|2493002', app(Choices::class)->all()[0]['options'][0]['value']);
    }

    public function test_a_qualifier_substring_does_not_select_a_different_state(): void
    {
        $this->campaign();
        $this->fakeDiscovery();

        $result = $this->tool(['cities' => ['Springfield, IN']]);

        $this->assertSame(['missing' => 1], $result['summary']);
        $this->assertSame([], app(Choices::class)->all());
    }

    public function test_confirmed_places_are_saved_together_and_publish_as_zips(): void
    {
        $campaign = $this->campaign();
        $discovery = $this->fakeDiscovery();
        $austin = $this->mapping('city', '2357536', 'Austin', 'Austin, Texas, US');
        $zip = $this->mapping('postal', 'US:94107', '94107', '94107, San Francisco, California, US');
        $discovery->shouldReceive('select')->with('meta', 'city', 'US', 'Austin', '2357536', 'act_123')->andReturn($austin);
        $discovery->shouldReceive('select')->with('meta', 'postal', 'US', '94107', 'US:94107', 'act_123')->andReturn($zip);
        $this->tool(['cities' => ['Austin'], 'postal_codes' => ['94107']]);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $applied = app(Answers::class)->applyAll([['field' => 'location_list_review', 'value' => ['city|2357536', 'postal|US:94107']]]);

        $this->assertTrue($applied[0]['applied']);
        $this->assertSame(['city', 'postal'], array_column(app(TargetingSelections::class)->reviewedCampaignPlaces($campaign->fresh()), 'kind'));
        $this->assertSame([
            'cities' => [['key' => '2357536']],
            'zips' => [['key' => 'US:94107']],
        ], app(TargetingSelections::class)->metaGeoLocations($campaign->fresh()));
    }

    public function test_a_place_that_was_not_offered_is_refused(): void
    {
        $campaign = $this->campaign();
        $this->fakeDiscovery();
        $this->tool(['cities' => ['Austin']]);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $result = $this->tool(['selected' => ['city|999']]);

        $this->assertFalse($result['ok']);
        $this->assertSame([], app(TargetingSelections::class)->reviewedCampaignPlaces($campaign->fresh()));
    }

    public function test_a_review_is_refused_once_targeting_has_changed(): void
    {
        $campaign = $this->campaign();
        $this->fakeDiscovery();
        $this->tool(['cities' => ['Austin']]);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        app(TargetingSelections::class)->chooseWholeCountries($campaign->fresh());

        $result = $this->tool(['selected' => ['city|2357536']]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('changed', $result['error']);
    }

    public function test_an_already_selected_place_is_not_offered_again(): void
    {
        $campaign = $this->campaign();
        $this->fakeDiscovery();
        app(TargetingSelections::class)->addCampaignLocation($campaign, $this->mapping('city', '2357536', 'Austin', 'Austin, Texas, US'));

        $result = $this->tool(['cities' => ['Austin']]);

        $this->assertSame(['already' => 1], $result['summary']);
        $this->assertSame([], app(Choices::class)->all());
    }

    public function test_an_oversized_list_is_refused_before_any_search(): void
    {
        $this->campaign();
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldNotReceive('search');
        $this->app->instance(LocationDiscovery::class, $discovery);

        $result = $this->tool(['postal_codes' => array_map('strval', range(10001, 10001 + LocationListResolver::MAX_ENTRIES))]);

        $this->assertFalse($result['ok']);
    }

    public function test_a_throttled_lookup_is_reported_instead_of_marking_every_place_missing(): void
    {
        $this->campaign();
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->andThrow(new MetaException('Application request limit reached', 80004));
        $this->app->instance(LocationDiscovery::class, $discovery);

        $result = $this->tool(['cities' => ['Austin']]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('request limit', $result['error']);
    }

    public function test_a_place_the_provider_rejects_carries_its_reason(): void
    {
        $this->campaign();
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->andThrow(new \InvalidArgumentException('Postal codes need a country.'));
        $this->app->instance(LocationDiscovery::class, $discovery);

        $result = $this->tool(['postal_codes' => ['94107']]);

        $this->assertSame(['94107' => 'Postal codes need a country.'], $result['reasons']);
    }

    public function test_the_location_question_offers_paste_a_list(): void
    {
        $campaign = $this->campaign();
        collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'campaign__choose_location')
            ->handle(new Request(['change_scope' => true]));
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $applied = app(Answers::class)->applyAll([['field' => 'location_scope', 'value' => 'list']]);

        $this->assertTrue($applied[0]['applied']);
        $this->assertSame('location_list', app(Choices::class)->all()[0]['field']);
        $this->assertNotNull($campaign);
    }

    public function test_the_specific_postal_code_choice_opens_a_postal_only_form(): void
    {
        $this->campaign();
        collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate) => $candidate->name() === 'campaign__choose_location')
            ->handle(new Request(['change_scope' => true]));
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $applied = app(Answers::class)->applyAll([['field' => 'location_scope', 'value' => 'postal']]);

        $this->assertTrue($applied[0]['applied']);
        $this->assertSame('location_list', app(Choices::class)->all()[0]['field']);
        $this->assertSame(['postal'], app(Choices::class)->all()[0]['location_list']['kinds']['US']);

        $this->tool();

        $this->assertSame(['postal'], app(Choices::class)->all()[0]['location_list']['kinds']['US']);
    }

    public function test_a_pasted_form_reaches_the_review(): void
    {
        $this->campaign();
        $this->fakeDiscovery();
        $this->tool();
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $applied = app(Answers::class)->applyAll([['field' => 'location_list', 'value' => [
            'country_code' => 'US', 'city' => "Austin\nAtlantis", 'postal' => '94107',
        ]]]);

        $this->assertTrue($applied[0]['applied']);
        $this->assertSame('location_list_review', app(Choices::class)->all()[0]['field']);
    }

    public function test_meta_readback_compares_zips(): void
    {
        $readback = app(PublishedLocationReadback::class);

        $this->assertSame(['US:94107'], $readback->normaliseMeta(['zips' => [['key' => 'US:94107']]])['zips']);
        $this->assertArrayNotHasKey('zips', $readback->normaliseMeta(['countries' => ['US']]));
    }

    /** @return array<string, array{string, string}> */
    public static function postalPlatforms(): array
    {
        return ['meta' => ['meta', 'US:94107'], 'google' => ['google', 'geoTargetConstants/9020000']];
    }

    #[DataProvider('postalPlatforms')]
    public function test_whole_country_and_explicit_clear_remove_postal_restrictions(string $platform, string $id): void
    {
        $campaign = $this->campaign($platform);
        $mapping = $this->mapping('postal', $id, '94107', '94107, California, US', $platform);
        $selections = app(TargetingSelections::class);
        $selections->addCampaignLocation($campaign, $mapping);
        $selections->chooseWholeCountries($campaign);

        $this->assertSame([], $selections->reviewedCampaignPlaces($campaign->fresh()));
        $this->assertSame(['US'], ($platform === 'meta'
            ? $selections->metaGeoLocations($campaign)
            : $selections->googleGeoTargets($campaign))['countries']);

        $selections->setPlaceIntentMode($campaign, 'override');
        $selections->addCampaignLocation($campaign, $mapping);
        $selections->setPlaceIntentMode($campaign, 'clear');

        $this->assertSame([], $selections->reviewedCampaignPlaces($campaign->fresh()));
    }

    #[DataProvider('postalPlatforms')]
    public function test_switching_from_whole_countries_to_postal_codes_passes_location_validation(string $platform, string $id): void
    {
        $campaign = $this->campaign($platform);
        $selections = app(TargetingSelections::class);
        $selections->chooseWholeCountries($campaign);
        $mapping = $this->mapping('postal', $id, '94107', '94107, California, US', $platform);
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->andReturn([$this->candidate('postal', $id, '94107', '94107, California, US')]);
        $discovery->shouldReceive('select')->once()->andReturn($mapping);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $this->tool(['postal_codes' => ['94107']]);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $result = $this->tool(['selected' => ['postal|'.$id]]);

        $this->assertTrue($result['ok']);
        $this->assertSame([], $selections->locationProblems($campaign->fresh()));
        $payload = $platform === 'meta' ? $selections->metaGeoLocations($campaign) : $selections->googleGeoTargets($campaign);
        $this->assertSame($platform === 'meta' ? [['key' => $id]] : [$id], $payload[$platform === 'meta' ? 'zips' : 'geo_targets']);
    }

    public function test_a_single_pasted_city_keeps_its_state_qualifier(): void
    {
        $this->campaign();
        $this->fakeDiscovery();

        foreach (['Springfield, Missouri', "Springfield, Missouri\n"] as $input) {
            $result = $this->tool(['cities' => $input]);
            $this->assertSame(['matched' => 1], $result['summary']);
            $this->assertSame('city|2493002', app(Choices::class)->all()[0]['options'][0]['value']);
        }

        $resolver = app(LocationListResolver::class);
        $this->assertSame(['Austin', 'Springfield, Missouri'], $resolver->split('Austin; Springfield, Missouri'));
        $this->assertSame(['94107', '10001', '90210'], $resolver->split("94107, 10001\n90210", commaSeparated: true));
    }

    public function test_two_names_for_the_same_place_offer_and_save_one_location(): void
    {
        $campaign = $this->campaign();
        $discovery = $this->fakeDiscovery();
        $discovery->shouldReceive('select')->once()->andReturn($this->mapping('city', '2357536', 'Austin', 'Austin, Texas, US'));

        $result = $this->tool(['cities' => ['Austin', 'Austin, Texas']]);
        $this->assertSame(['matched' => 1], $result['summary']);
        $this->assertCount(1, app(Choices::class)->all()[0]['options']);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $this->assertTrue($this->tool(['selected' => ['city|2357536', 'city|2357536']])['ok']);
        $this->assertCount(1, app(TargetingSelections::class)->reviewedCampaignPlaces($campaign->fresh()));
    }

    public function test_two_different_choices_for_one_ambiguous_entry_are_still_refused(): void
    {
        $campaign = $this->campaign();
        $this->fakeDiscovery();
        $this->tool(['cities' => ['Springfield']]);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $this->assertFalse($this->tool(['selected' => ['city|2493001', 'city|2493002']])['ok']);
        $this->assertSame([], app(TargetingSelections::class)->reviewedCampaignPlaces($campaign->fresh()));
    }
}
