<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Publishing\GooglePublisher;
use App\Models\Asset;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Laravel\Ai\Tools\Request;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

/**
 * A Performance Max campaign is asked which creative is its logo.
 *
 * Google will not run an asset group without one, and will not accept a
 * marketing image in its place: a product shot sent as a logo is refused as not
 * being a logo. Nothing in the flow collected one, so no Performance Max
 * campaign could ever have served - which the account bears out, having no
 * asset groups at all.
 *
 * It is asked rather than guessed. Of the ways to find one - reuse a square
 * marketing image, keep one per account, scrape it off the landing page - each
 * picks something that is usually not the brand mark, and the failure is a
 * policy refusal rather than a cosmetic one. The buyer naming it is the only
 * version that is reliably right.
 *
 * Asked where the creatives are already being decided, and refused at publish
 * if it never was, for the same reason the image shapes are: Google rejecting
 * the asset group after the campaign and budget exist turns a clear question
 * into an opaque failure and a rollback.
 */
class APerformanceMaxCampaignAsksForItsLogoTest extends TestCase
{
    use RefreshDatabase, SeedsVerifiedCountries;

    private User $user;

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

        $this->seedVerifiedCountries();
        Storage::fake('local');

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

        app(Workspace::class)->bindTo('conv-pmax-logo');
        app(Workspace::class)->ownedBy($this->user);

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

        $resource = fn (string $path): array => ['results' => [['resourceName' => $path]]];

        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*assets:mutate' => Http::response($resource('customers/1234567890/assets/99')),
            '*campaignBudgets:mutate' => Http::response($resource('customers/1234567890/campaignBudgets/111')),
            '*campaigns:mutate' => Http::response($resource('customers/1234567890/campaigns/222')),
            '*assetGroups:mutate' => Http::response($resource('customers/1234567890/assetGroups/333')),
            '*:mutate' => Http::response(['results' => []]),
            '*googleAds:searchStream' => Http::response([['results' => []]]),
        ]);
    }

    private function campaign(string $type = 'performance_max'): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Knowledgedom PMax',
            'platform' => 'google',
            'status' => 'draft',
            'campaign_type' => $type,
            'ad_account_id' => '1234567890',
            'landing_url' => 'https://example.com/offer',
            'objective' => 'LEADS',
            'budget' => 50,
            'budget_mode' => 'daily',
            'currency' => 'USD',
            'bid_strategy' => 'MAXIMIZE_CONVERSIONS',
            'locations' => ['countries' => ['US']],
            'placements' => ['search'],
            'utm' => '',
        ]);

        foreach (['Block annoying ads', 'Browse faster today', 'Private browsing'] as $headline) {
            CampaignAd::create([
                'campaign_id' => $campaign->id,
                'headline' => $headline,
                'description' => 'Stop trackers and pop ups.',
                'primary_text' => 'Stop trackers and pop ups.',
                'cta' => 'LEARN_MORE',
                'status' => 'draft',
            ]);
        }

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

        return $campaign->fresh();
    }

    private function image(string $name, int $width, int $height): Asset
    {
        $image = imagecreatetruecolor($width, $height);
        ob_start();
        imagepng($image);
        $bytes = (string) ob_get_clean();
        imagedestroy($image);

        Storage::disk('local')->put($name, $bytes);

        $asset = Asset::create([
            'user_id' => $this->user->id,
            'kind' => 'image',
            'disk' => 'local',
            'path' => $name,
            'original_name' => $name,
        ]);

        app(Workspace::class)->produced($asset, focus: false);

        return $asset;
    }

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

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

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

    private function publish(Campaign $campaign): array
    {
        $created = [];

        try {
            app(GooglePublisher::class)->create($campaign, 'tester', $created);

            return ['ok' => true, 'error' => null];
        } catch (\Throwable $e) {
            return ['ok' => false, 'error' => $e->getMessage()];
        }
    }

    // ------------------------------------------------------------- the asking

    /** Attaching creatives says a logo is still needed, and offers the squares. */
    public function test_attaching_creatives_asks_which_one_is_the_logo(): void
    {
        $this->campaign();
        $this->image('wide.png', 1200, 628);
        $logo = $this->image('logo.png', 512, 512);

        $result = $this->attach();

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertTrue($result['logo_needed']);
        $this->assertSame([$logo->id], array_column($result['logo_candidates'], 'asset_id'));
        $this->assertStringContainsString('Ask which of the squares listed is the logo', $result['note']);
    }

    /** And it is told not to pick one itself. */
    public function test_the_model_is_told_not_to_choose_the_logo(): void
    {
        $this->campaign();
        $this->image('logo.png', 512, 512);

        $this->assertStringContainsString('Do not pick one yourself', $this->attach()['note']);
    }

    /** With no square attached, the answer is an upload rather than a choice. */
    public function test_with_no_square_attached_it_asks_for_an_upload(): void
    {
        $this->campaign();
        $this->image('wide.png', 1200, 628);

        $result = $this->attach();

        $this->assertSame([], $result['logo_candidates']);
        $this->assertStringContainsString('ask the user to upload the logo', $result['note']);
    }

    /** Once named, it stops being asked for. */
    public function test_naming_the_logo_records_it_and_stops_the_question(): void
    {
        $campaign = $this->campaign();
        $this->image('wide.png', 1200, 628);
        $logo = $this->image('logo.png', 512, 512);

        $result = $this->attach(['logo_asset_id' => $logo->id]);

        $this->assertSame($logo->id, $campaign->fresh()->meta['google_logo_asset_id']);
        $this->assertArrayNotHasKey('logo_needed', $result);
    }

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

    /** A marketing image is not a logo, and is refused as one. */
    public function test_a_non_square_creative_cannot_be_named_as_the_logo(): void
    {
        $campaign = $this->campaign();
        $wide = $this->image('wide.png', 1200, 628);

        $result = $this->attach(['logo_asset_id' => $wide->id]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('square image of at least 128x128', $result['error']);
        $this->assertNull($campaign->fresh()->meta['google_logo_asset_id'] ?? null);
    }

    /** A square too small for Google is refused too. */
    public function test_a_square_below_googles_minimum_is_refused(): void
    {
        $this->campaign();
        $tiny = $this->image('tiny.png', 64, 64);

        $result = $this->attach(['logo_asset_id' => $tiny->id]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('at least 128x128', $result['error']);
    }

    /** An id that is not attached to the conversation is refused. */
    public function test_an_unattached_asset_cannot_be_the_logo(): void
    {
        $this->campaign();
        $this->image('logo.png', 512, 512);

        $result = $this->attach(['logo_asset_id' => 999999]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('not attached to this conversation', $result['error']);
    }

    /** Only Performance Max has the question at all. */
    public function test_a_search_campaign_is_never_asked_for_a_logo(): void
    {
        $this->campaign('search');
        $this->image('logo.png', 512, 512);

        $this->assertArrayNotHasKey('logo_needed', $this->attach());
    }

    public function test_naming_a_logo_on_a_non_pmax_campaign_is_refused(): void
    {
        $this->campaign('display');
        $logo = $this->image('logo.png', 512, 512);

        $result = $this->attach(['logo_asset_id' => $logo->id]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('only asked for on a Google Performance Max campaign', $result['error']);
    }

    // -------------------------------------------------------------- at publish

    /**
     * Refused before the campaign and budget exist, not after Google rejects it.
     *
     * The same shape as the image refusal: a clear question here beats an
     * opaque failure and a rollback there.
     */
    public function test_publishing_without_a_logo_is_refused_before_anything_is_created(): void
    {
        $campaign = $this->campaign();
        $wide = $this->image('wide.png', 1200, 628);
        $square = $this->image('square.png', 1200, 1200);

        // Both image shapes present, so the only thing missing is the logo.
        $campaign->ads()->get()->each(fn ($ad, $index) => $ad->update(
            ['asset_id' => $index === 0 ? $wide->id : $square->id],
        ));

        $result = $this->publish($campaign->fresh());

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('no brand logo', $result['error']);
        $this->assertStringContainsString('attach_creatives', $result['error']);

        $created = collect(Http::recorded())
            ->contains(fn (array $pair): bool => str_contains($pair[0]->url(), '/campaigns:mutate'));

        $this->assertFalse($created, 'a campaign was created before the logo was checked');
    }

    /**
     * The publisher checks the size too, not only the tool that recorded it.
     *
     * A recorded choice can stop being valid without passing through
     * attach_creatives again: a duplicated campaign carries the id across, and
     * the file behind an asset can be replaced. Checking only where it is
     * chosen would send Google something it refuses.
     */
    public function test_a_recorded_logo_that_is_not_square_is_refused_at_publish(): void
    {
        $campaign = $this->campaign();
        $wide = $this->image('wide.png', 1200, 628);
        $square = $this->image('square.png', 1200, 1200);

        $campaign->ads()->get()->each(fn ($ad, $index) => $ad->update(
            ['asset_id' => $index === 0 ? $wide->id : $square->id],
        ));

        // Set straight onto the campaign, the way a duplicate or an import
        // would, bypassing the check in attach_creatives.
        $campaign->update(['meta' => ['google_logo_asset_id' => $wide->id]]);

        $result = $this->publish($campaign->fresh());

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('1200x628', $result['error']);
        $this->assertStringContainsString('square of at least 128x128', $result['error']);
    }

    /** With one named, the asset group gets a LOGO link. */
    public function test_a_named_logo_reaches_the_asset_group(): void
    {
        $campaign = $this->campaign();
        $wide = $this->image('wide.png', 1200, 628);
        $square = $this->image('square.png', 1200, 1200);
        $logo = $this->image('logo.png', 512, 512);

        $campaign->ads()->get()->each(fn ($ad, $i) => $ad->update(['asset_id' => $i === 0 ? $wide->id : $square->id]));
        $this->attach(['logo_asset_id' => $logo->id]);

        $this->assertTrue($this->publish($campaign->fresh())['ok']);

        $fields = collect(Http::recorded())
            ->filter(fn (array $pair): bool => str_contains($pair[0]->url(), '/assetGroupAssets:mutate'))
            ->flatMap(fn (array $pair): array => (array) ($pair[0]->data()['operations'] ?? []))
            ->map(fn (array $operation): mixed => $operation['create']['fieldType'] ?? null)
            ->all();

        $this->assertContains('LOGO', $fields);
    }
}
