<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\Location;
use App\Models\PlatformLocation;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request as ToolRequest;
use RuntimeException;
use Tests\TestCase;

class SharedPlaceIntentTest extends TestCase
{
    use RefreshDatabase;

    private function campaign(Brief $brief, string $platform): Campaign
    {
        return Campaign::create([
            'user_id' => $brief->user_id,
            'brief_id' => $brief->getKey(),
            'name' => ucfirst($platform).' local campaign',
            'platform' => $platform,
            'status' => 'draft',
            'locations' => ['countries' => ['US']],
            'ad_account_id' => '1234567890',
        ]);
    }

    private function place(string $platform, string $externalId, string $parent): PlatformLocation
    {
        $location = Location::factory()->create([
            'type' => 'city',
            'name' => 'Springfield',
            'iso_code' => null,
            'country_code' => 'US',
            'source' => $platform,
            'source_key' => $externalId,
        ]);

        return PlatformLocation::factory()->create([
            'location_id' => $location->getKey(),
            'platform' => $platform,
            'external_id' => $externalId,
            'provider_name' => 'Springfield, '.$parent.', United States',
        ]);
    }

    public function test_shared_city_requires_an_explicit_exact_provider_selection_on_the_next_platform(): void
    {
        $brief = Brief::factory()->create(['locations' => ['countries' => ['US']]]);
        $meta = $this->campaign($brief, 'meta');
        $google = $this->campaign($brief, 'google');
        $selections = app(TargetingSelections::class);
        $selections->addCampaignLocation($meta, $this->place('meta', '2420605', 'Illinois'));

        $intent = $selections->sharedPlaceIntents($google->fresh());
        $this->assertCount(1, $intent);
        $this->assertSame('Springfield, Illinois, United States', $intent[0]['label']);
        $this->assertNull($brief->fresh()->targetingSet->locations()->where('kind', 'city')->first()->platform_location_id);
        $this->assertSame($intent, $selections->pendingSharedPlaces($google->fresh()));
        $this->assertStringContainsString('exact Google place selection', $selections->locationProblems($google->fresh())[0]);

        $googlePlace = $this->place('google', 'geoTargetConstants/123', 'Illinois');
        $selections->addCampaignLocation($google, $googlePlace, sharedPlaceId: $intent[0]['id']);

        $this->assertSame([], $selections->pendingSharedPlaces($google->fresh()));
        $this->assertSame(['US'], $selections->countries($google->fresh()));
        $this->assertSame(['countries' => [], 'geo_targets' => ['geoTargetConstants/123']], $selections->googleGeoTargets($google->fresh()));

        $googlePlace->update(['provider_name' => 'Springfield, Missouri, United States']);
        $this->assertCount(1, $selections->pendingSharedPlaces($google->fresh()));
    }

    public function test_explicit_whole_country_choice_clears_shared_city_intent(): void
    {
        $brief = Brief::factory()->create(['locations' => ['countries' => ['US']]]);
        $meta = $this->campaign($brief, 'meta');
        $google = $this->campaign($brief, 'google');
        $selections = app(TargetingSelections::class);
        $selections->addCampaignLocation($meta, $this->place('meta', '2420605', 'Illinois'));

        $this->assertCount(1, $selections->pendingSharedPlaces($google));

        $set = $selections->chooseWholeCountries($google);

        $this->assertSame('whole', $set->options['geography_scope']);
        $this->assertSame('clear', $set->options['place_intent_mode']);
        $this->assertSame([], $selections->pendingSharedPlaces($google->fresh()));
        $this->assertTrue($selections->hasChosenGeographyScope($google->fresh()));
    }

    public function test_ambiguous_or_implicit_cross_platform_match_cannot_resolve_shared_intent(): void
    {
        $brief = Brief::factory()->create(['locations' => ['countries' => ['US']]]);
        $meta = $this->campaign($brief, 'meta');
        $google = $this->campaign($brief, 'google');
        $selections = app(TargetingSelections::class);
        $selections->addCampaignLocation($meta, $this->place('meta', '2420605', 'Illinois'));
        $intentId = $selections->sharedPlaceIntents($google)[0]['id'];
        $illinois = $this->place('google', 'geoTargetConstants/123', 'Illinois');
        $missouri = $this->place('google', 'geoTargetConstants/456', 'Missouri');

        try {
            $selections->addCampaignLocation($google, $illinois);
            $this->fail('Expected an explicit shared place choice.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('shared_place_id', $exception->getMessage());
        }

        try {
            $selections->addCampaignLocation($google, $missouri, sharedPlaceId: $intentId);
            $this->fail('Expected a parent mismatch.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('does not match', $exception->getMessage());
        }

        $this->assertNull($google->fresh()->targetingSet);
        $this->assertCount(1, $selections->pendingSharedPlaces($google->fresh()));
    }

    public function test_removal_reopens_shared_intent_and_clear_or_override_survives_reload(): void
    {
        $brief = Brief::factory()->create(['locations' => ['countries' => ['US']]]);
        $meta = $this->campaign($brief, 'meta');
        $google = $this->campaign($brief, 'google');
        $selections = app(TargetingSelections::class);
        $selections->addCampaignLocation($meta, $this->place('meta', '2420605', 'Illinois'));
        $intentId = $selections->sharedPlaceIntents($google)[0]['id'];
        $googlePlace = $this->place('google', 'geoTargetConstants/123', 'Illinois');
        $selections->addCampaignLocation($google, $googlePlace, sharedPlaceId: $intentId);
        $selections->removeCampaignLocation($google, 'US', 'geoTargetConstants/123');

        $this->assertCount(1, $selections->pendingSharedPlaces($google->fresh()));

        $set = $selections->setPlaceIntentMode($google, 'clear');
        $this->assertSame('clear', $set->fresh()->options['place_intent_mode']);
        $this->assertTrue($selections->hasChosenGeographyScope($google->fresh()));
        $this->assertSame([], $selections->pendingSharedPlaces($google->fresh()));
        $this->assertSame(['countries' => ['US'], 'geo_targets' => []], $selections->googleGeoTargets($google->fresh()));

        try {
            $selections->addCampaignLocation($google, $this->place('google', 'geoTargetConstants/455', 'Missouri'));
            $this->fail('A cleared campaign should remain whole-country until the user chooses an override.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('Choose different places', $exception->getMessage());
        }

        $selections->setPlaceIntentMode($google, 'override', expectedRevision: $set->revision);
        $this->assertFalse($selections->hasChosenGeographyScope($google->fresh()));
        $selections->addCampaignLocation($google, $this->place('google', 'geoTargetConstants/456', 'Missouri'));
        $this->assertSame([], $selections->pendingSharedPlaces($google->fresh()));
        $this->assertSame(['geoTargetConstants/456'], $selections->googleGeoTargets($google->fresh())['geo_targets']);
        $this->assertCount(1, $selections->sharedPlaceIntents($google->fresh()));
    }

    public function test_override_discards_previously_inherited_places_before_new_selection(): void
    {
        $brief = Brief::factory()->create(['locations' => ['countries' => ['US']]]);
        $meta = $this->campaign($brief, 'meta');
        $google = $this->campaign($brief, 'google');
        $selections = app(TargetingSelections::class);
        $selections->addCampaignLocation($meta, $this->place('meta', '2420605', 'Illinois'));
        $intentId = $selections->sharedPlaceIntents($google)[0]['id'];
        $selections->addCampaignLocation($google, $this->place('google', 'geoTargetConstants/123', 'Illinois'), sharedPlaceId: $intentId);

        $selections->setPlaceIntentMode($google, 'override');

        $this->assertSame([], $selections->selectedCampaignLocations($google->fresh(), 'US'));
        $this->assertSame([], $selections->pendingSharedPlaces($google->fresh()));
        $this->assertSame(['countries' => ['US'], 'geo_targets' => []], $selections->googleGeoTargets($google->fresh()));
        $this->assertStringContainsString('replacement city or state', $selections->locationProblems($google->fresh())[0]);

        $selections->addCampaignLocation($google, $this->place('google', 'geoTargetConstants/456', 'Missouri'));
        $this->assertSame([], $selections->locationProblems($google->fresh()));
    }

    public function test_linkedin_requires_a_choice_on_the_correct_campaign_before_clearing_shared_places(): void
    {
        $brief = Brief::factory()->create(['locations' => ['countries' => ['US']]]);
        $meta = $this->campaign($brief, 'meta');
        $linkedin = $this->campaign($brief, 'linkedin');
        $otherLinkedin = $this->campaign($brief, 'linkedin');
        $selections = app(TargetingSelections::class);
        $selections->addCampaignLocation($meta, $this->place('meta', '2420605', 'Illinois'));
        $this->assertStringContainsString('Linkedin', $selections->locationProblems($linkedin)[0]);

        $workspace = app(Workspace::class);
        $workspace->bindTo('shared-place-intent-test');
        $workspace->focusOn($linkedin);
        $tool = collect(app(ToolRegistry::class)->resolve())->first(fn ($candidate): bool => $candidate->name() === 'campaign__choose_location');
        $this->assertNotNull($tool);

        $unoffered = json_decode((string) $tool->handle(new ToolRequest(['place_intent_mode' => 'clear'])), true);
        $this->assertFalse($unoffered['ok']);

        $shown = json_decode((string) $tool->handle(new ToolRequest([])), true);
        $this->assertFalse($shown['ok']);
        $this->assertCount(1, $shown['pending_shared_places']);
        $workspace->rememberChoices(app(Choices::class)->all());
        $workspace->focusOn($otherLinkedin);
        $wrongCampaign = json_decode((string) $tool->handle(new ToolRequest(['place_intent_mode' => 'clear'])), true);
        $this->assertFalse($wrongCampaign['ok']);

        $workspace->focusOn($linkedin);
        $cleared = json_decode((string) $tool->handle(new ToolRequest(['place_intent_mode' => 'clear'])), true);
        $this->assertTrue($cleared['ok']);
        $this->assertSame([], $selections->locationProblems($linkedin->fresh()));
        $this->assertCount(1, $selections->pendingSharedPlaces($otherLinkedin->fresh()));
    }
}
