<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Platforms\GoogleRules;
use App\Campaigns\Platforms\MetaRules;
use App\Campaigns\PublishGate;
use App\Campaigns\Publishing\GooglePublisher;
use App\Campaigns\Targeting\SearchKeywordSelections;
use App\Models\ArtifactFieldSource;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

/**
 * Google ad copy is written as Google takes it, not as Meta takes it.
 *
 * Mohsin, testing the flow on 15 Oct: "in google we have headlines upto 15 with
 * 30 character limit ... it is giving me meta specific suggestions".
 *
 * He was right, and the cause was the shape rather than the limits. The limits
 * were already correct at 30 and 90. What was Meta's was the model: write_ad_copy
 * took a list of variations, each a headline plus body plus a required call to
 * action, and a responsive search ad is not that. It is one ad built from a pool
 * of up to fifteen headlines and four descriptions that Google mixes per
 * auction.
 *
 * Expressed as variations, fifteen headlines meant fifteen rows, each carrying
 * a body and a button Google has no use for, against max_ads_per_publish of
 * five. So three was what the model wrote and five was the ceiling, on a format
 * that takes fifteen.
 *
 * Two things had to change together: the tool had to accept the pool, and the
 * cap had to stop counting the assets of one ad as separate ads.
 */
class GoogleAdCopyIsWrittenInGooglesShapeTest extends TestCase
{
    use RefreshDatabase, SeedsVerifiedCountries;

    private User $user;

    protected function setUp(): void
    {
        parent::setUp();

        $this->user = User::factory()->create();
        $this->actingAs($this->user);

        // Publishing maps country codes through the catalog, so the two tests
        // that run a real publish need it present.
        $this->seedVerifiedCountries();

        app(Workspace::class)->bindTo('conv-google-copy-shape');
        app(Workspace::class)->ownedBy($this->user);

        config([
            'platforms.guardrails.allowed_ad_accounts' => ['3460855874'],
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '3460855874',
        ]);
    }

    private function campaign(string $platform = 'google'): Campaign
    {
        $brief = Brief::create([
            'user_id' => $this->user->id,
            'landing_url' => 'https://example.com/offer',
            'page_analysis' => ['url' => 'https://example.com/offer', 'title' => 'Car insurance'],
        ]);

        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'brief_id' => $brief->id,
            'name' => 'Knowledgedom',
            'platform' => $platform,
            'status' => 'draft',
            'campaign_type' => $platform === 'google' ? 'search' : null,
            'ad_account_id' => '3460855874',
            'landing_url' => 'https://example.com/offer',
            'objective' => $platform === 'google' ? 'LEADS' : 'OUTCOME_LEADS',
            'locations' => ['countries' => ['US']],
            'budget' => 50,
            'budget_mode' => 'daily',
            'audience' => ['devices' => ['mobile']],
            'placements' => [$platform === 'google' ? 'search' : 'facebook'],
            'bid_strategy' => 'MAXIMIZE_CONVERSIONS',
        ]);

        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);

        // The highlight question is a step of its own, and copy is refused
        // until it has been answered.
        app(Workspace::class)->recordSource($campaign, 'copy_emphasis', ArtifactFieldSource::USER_STATED);

        return $campaign;
    }

    private function write(array $arguments): array
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t): bool => $t->name() === 'campaign__write_ad_copy');

        $this->assertNotNull($tool, 'campaign__write_ad_copy is not registered');

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

    /** @return list<string> */
    private function headlines(int $count): array
    {
        return collect(range(1, $count))->map(fn (int $i): string => 'Car cover option '.$i)->all();
    }

    private function pool(int $headlines = 15, int $descriptions = 4): array
    {
        return [
            'headlines' => $this->headlines($headlines),
            'descriptions' => collect(range(1, $descriptions))
                ->map(fn (int $i): string => 'Compare cover and save on your policy today, option '.$i.'.')
                ->all(),
        ];
    }

    // ------------------------------------------------------ the shape itself

    /** Fifteen headlines, which the variation model could never express. */
    public function test_fifteen_headlines_can_be_written(): void
    {
        $campaign = $this->campaign();

        $result = $this->write($this->pool());

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertCount(15, $result['headlines']);
        $this->assertSame(15, $campaign->ads()->count());
    }

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

        $result = $this->write($this->pool(descriptions: 4));

        $this->assertCount(4, $result['descriptions']);
    }

    /** No call to action is asked for or stored as a decision. */
    public function test_no_call_to_action_is_required(): void
    {
        $this->campaign();

        $result = $this->write($this->pool());

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertStringContainsString('no call-to-action button', $result['note']);
    }

    /** The final URL is shown, because this step is where a buyer would check it. */
    public function test_the_final_url_is_surfaced(): void
    {
        $this->campaign();

        $this->assertSame('https://example.com/offer', $this->write($this->pool())['final_url']);
    }

    // ------------------------------------------------- what the publisher reads

    /**
     * The rows are built so the publisher reconstructs the pool exactly.
     *
     * It collects every row's headline into one ad, and every row's description
     * and body into that ad's descriptions, deduped. So filler in primary_text
     * would surface in the live ad as a description nobody wrote.
     */
    public function test_no_filler_reaches_the_descriptions(): void
    {
        $campaign = $this->campaign();

        $this->write($this->pool(headlines: 15, descriptions: 2));

        $bodies = $campaign->ads()->pluck('primary_text')->unique()->values()->all();

        $this->assertSame([
            'Compare cover and save on your policy today, option 1.',
            'Compare cover and save on your policy today, option 2.',
        ], $bodies, 'something other than a real description was stored as body text');
    }

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

        $this->write($this->pool(headlines: 5, descriptions: 2));

        $this->assertSame($this->headlines(5), $campaign->ads()->orderBy('id')->pluck('headline')->all());
    }

    // ------------------------------------------------------------ the old cap

    /**
     * Fifteen rows are one ad, so the five-ad cap does not refuse them.
     *
     * The cap is on how much one approval may create. One approval creates one
     * responsive search ad here however many headlines it carries, which is
     * what PlatformRules::buildsOneAdFromEveryVariation says.
     */
    public function test_fifteen_headlines_do_not_trip_the_five_ad_cap(): void
    {
        $campaign = $this->campaign();

        $this->write($this->pool());

        $refusals = collect(app(PublishGate::class)->check($campaign->fresh()))
            ->filter(fn (string $reason): bool => str_contains($reason, 'at most'));

        $this->assertSame([], $refusals->values()->all(), 'the publish gate counted the headlines as ads');
    }

    /** Meta still gets one ad per variation, and still has its cap. */
    public function test_meta_still_counts_every_variation_as_an_ad(): void
    {
        $this->assertFalse(app(MetaRules::class)->buildsOneAdFromEveryVariation());
        $this->assertTrue(app(GoogleRules::class)->buildsOneAdFromEveryVariation());
    }

    // -------------------------------------------------------- display paths

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

        $result = $this->write([...$this->pool(), 'path1' => 'insurance', 'path2' => 'quotes']);

        $this->assertSame(['path1' => 'insurance', 'path2' => 'quotes'], $result['display_paths']);
        $this->assertSame(['path1' => 'insurance', 'path2' => 'quotes'], $campaign->fresh()->meta['google_display_paths']);
    }

    /**
     * And they reach the ad, not just the campaign row.
     *
     * Storing them and never sending them would look identical in the chat:
     * the tool reports the paths, the panel shows them, and the live ad does
     * not have them.
     */
    public function test_display_paths_reach_the_responsive_search_ad(): void
    {
        $campaign = $this->campaign();

        $this->write([...$this->pool(headlines: 3), 'path1' => 'insurance', 'path2' => 'quotes']);

        app(SearchKeywordSelections::class)->save($campaign->fresh(), [
            ['text' => 'car insurance', 'match_type' => 'PHRASE', 'negative' => false],
        ], 0);

        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => Http::response([['results' => []]]),
            '*:mutate' => Http::response(['results' => [['resourceName' => 'customers/3460855874/adGroupAds/1~2']]]),
        ]);

        $created = [];
        app(GooglePublisher::class)->create($campaign->fresh(), 'tester', $created);

        $rsa = collect(Http::recorded())
            ->filter(fn (array $pair): bool => str_contains($pair[0]->url(), '/adGroupAds:mutate'))
            ->map(fn (array $pair): mixed => data_get($pair[0]->data(), 'operations.0.create.ad.responsiveSearchAd'))
            ->first();

        $this->assertNotNull($rsa, 'no responsive search ad was sent');
        $this->assertSame('insurance', $rsa['path1']);
        $this->assertSame('quotes', $rsa['path2']);
    }

    /** With none given, nothing is sent: Google refuses a blank display path. */
    public function test_no_display_path_is_sent_when_none_was_given(): void
    {
        $campaign = $this->campaign();

        $this->write($this->pool(headlines: 3));

        app(SearchKeywordSelections::class)->save($campaign->fresh(), [
            ['text' => 'car insurance', 'match_type' => 'PHRASE', 'negative' => false],
        ], 0);

        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => Http::response([['results' => []]]),
            '*:mutate' => Http::response(['results' => [['resourceName' => 'customers/3460855874/adGroupAds/1~2']]]),
        ]);

        $created = [];
        app(GooglePublisher::class)->create($campaign->fresh(), 'tester', $created);

        $rsa = collect(Http::recorded())
            ->filter(fn (array $pair): bool => str_contains($pair[0]->url(), '/adGroupAds:mutate'))
            ->map(fn (array $pair): mixed => data_get($pair[0]->data(), 'operations.0.create.ad.responsiveSearchAd'))
            ->first();

        $this->assertNotNull($rsa);
        $this->assertArrayNotHasKey('path1', $rsa);
        $this->assertArrayNotHasKey('path2', $rsa);
    }

    /** A slash means the model is building a URL rather than naming a path. */
    public function test_a_display_path_with_a_slash_is_refused(): void
    {
        $this->campaign();

        $result = $this->write([...$this->pool(), 'path1' => 'car/insurance']);

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

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

        $result = $this->write([...$this->pool(), 'path1' => 'comprehensive-cover-options']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('at most 15 characters', $result['error']);
    }

    // ------------------------------------------------------------- refusals

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

        $result = $this->write($this->pool(headlines: 2));

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('takes 3 to 15', $result['error']);
        $this->assertSame(0, $campaign->ads()->count());
    }

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

        $result = $this->write($this->pool(headlines: 16));

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('takes 3 to 15', $result['error']);
    }

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

        $result = $this->write($this->pool(descriptions: 5));

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('takes 1 to 4', $result['error']);
    }

    /** Over the limit Google truncates rather than refusing, so this does. */
    public function test_a_headline_over_thirty_characters_is_refused(): void
    {
        $this->campaign();

        $pool = $this->pool();
        $pool['headlines'][0] = 'This headline is far too long for a Google search ad';

        $result = $this->write($pool);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('A Google headline takes 30', $result['error']);
    }

    /** Duplicates are collapsed before counting, not silently published twice. */
    public function test_duplicate_headlines_are_counted_once(): void
    {
        $this->campaign();

        $pool = $this->pool(headlines: 4);
        $pool['headlines'][3] = $pool['headlines'][0];

        $result = $this->write($pool);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertCount(3, $result['headlines']);
    }

    // ---------------------------------------------------- Meta is untouched

    /** A Meta campaign still goes through the variation path. */
    public function test_meta_still_takes_variations(): void
    {
        $campaign = $this->campaign('meta');

        $result = $this->write(['ads' => [
            ['headline' => 'Cheap cover', 'primary_text' => 'Compare today.', 'cta' => 'LEARN_MORE'],
            ['headline' => 'Fast quotes', 'primary_text' => 'Two minutes.', 'cta' => 'LEARN_MORE'],
        ]]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(2, $campaign->ads()->count());
        $this->assertSame(['LEARN_MORE', 'LEARN_MORE'], $campaign->ads()->pluck('cta')->all());
    }

    /** And a Google campaign given variations still works, as it did before. */
    public function test_google_still_accepts_variations_when_given_them(): void
    {
        $campaign = $this->campaign();

        $result = $this->write(['ads' => [
            ['headline' => 'Cheap cover', 'primary_text' => 'Compare today.', 'cta' => 'LEARN_MORE'],
            ['headline' => 'Fast quotes', 'primary_text' => 'Two minutes.', 'cta' => 'LEARN_MORE'],
            ['headline' => 'Save money', 'primary_text' => 'Switch now.', 'cta' => 'LEARN_MORE'],
        ]]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(3, $campaign->ads()->count());
    }

    /** Rewriting the pool replaces the previous one rather than adding to it. */
    public function test_writing_again_replaces_the_previous_pool(): void
    {
        $campaign = $this->campaign();

        $this->write($this->pool(headlines: 10));
        $this->write($this->pool(headlines: 4));

        $this->assertSame(4, $campaign->ads()->count());
    }

    /** Published ads are never replaced by a rewrite. */
    public function test_a_published_ad_is_left_alone(): void
    {
        $campaign = $this->campaign();

        CampaignAd::create([
            'campaign_id' => $campaign->id,
            'ad_set_id' => $campaign->primaryAdSet->id,
            'headline' => 'Live headline',
            'primary_text' => 'Live body.',
            'cta' => 'LEARN_MORE',
            'external_ad_id' => 'ad-1',
        ]);

        $this->write($this->pool(headlines: 3));

        $this->assertSame(1, $campaign->ads()->whereNotNull('external_ad_id')->count());
        $this->assertSame(4, $campaign->ads()->count());
    }
}
