<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Models\Asset;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * attach_creatives leaves ads that are already on Meta alone.
 *
 * The image is part of the creative, and Meta will not swap one out. So
 * repointing a live ad's asset_id changed nothing on the platform: the ad went
 * on serving the image it launched with while our row named a different one.
 * Two things followed from that. The buyer was told the creative had been
 * changed when it had not, and the copy fingerprint drifted, so the campaign
 * began reporting that it needed a rebuild for a change nobody had made.
 *
 * Neither tool had any notion of a published campaign - attach_creatives wrote
 * asset_id over every ad it found, and choose_call_to_action wrote cta over
 * every ad it found. WriteAdCopy had the right idea already, keying on
 * external_ad_id and leaving live ads to be added beside rather than rewritten;
 * these now do the same, and name edit_entity as the thing that does change a
 * live ad, by building a new creative under it.
 */
class CreativesAreNotRepointedOnLiveAdsTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

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

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

        app(Workspace::class)->bindTo('conv-creatives-live');
        app(Workspace::class)->ownedBy($this->user);
    }

    private function campaign(): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'published',
            'ad_account_id' => 'act_111',
            'external_campaign_id' => '120252047635070626',
        ]);

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

        return $campaign;
    }

    private function asset(string $path = 'assets/a.png'): Asset
    {
        $asset = Asset::create(['kind' => 'image', 'source' => 'upload', 'path' => $path]);

        // An artifact of the conversation, but focus stays on the campaign -
        // which is the real state when this tool runs, and what produced()
        // would otherwise take away.
        app(Workspace::class)->produced($asset, focus: false);

        return $asset;
    }

    private function ad(Campaign $campaign, ?string $externalId = null, ?int $assetId = null): CampaignAd
    {
        return $campaign->ads()->create([
            'headline' => 'Headline',
            'primary_text' => 'Body.',
            'cta' => 'LEARN_MORE',
            'asset_id' => $assetId,
            'external_ad_id' => $externalId,
            'status' => $externalId === null ? 'draft' : 'published',
        ]);
    }

    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);
    }

    // ------------------------------------------------------- spreading them

    /** The defect: a live ad's creative was repointed with no platform call. */
    public function test_spreading_does_not_repoint_a_live_ad(): void
    {
        $campaign = $this->campaign();
        $old = $this->asset('assets/old.png');
        $this->asset('assets/new.png');

        $live = $this->ad($campaign, externalId: 'ad-1', assetId: $old->id);

        $this->ad($campaign);

        $this->attach();

        $this->assertSame($old->id, $live->fresh()->asset_id, 'the live ad was repointed at a different image');
    }

    /** The draft beside it is still filled, which is what the tool is for. */
    public function test_spreading_still_fills_the_drafts(): void
    {
        $campaign = $this->campaign();
        $asset = $this->asset();

        $this->ad($campaign, externalId: 'ad-1');
        $draft = $this->ad($campaign);

        $result = $this->attach();

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame($asset->id, $draft->fresh()->asset_id);
    }

    /** And the reply says which were left, so the chat does not claim them. */
    public function test_spreading_names_the_live_ads_it_left(): void
    {
        $campaign = $this->campaign();
        $this->asset();

        $this->ad($campaign, externalId: 'ad-1');
        $this->ad($campaign);

        $result = $this->attach();

        $this->assertSame(['ad-1'], $result['left_alone_because_they_are_live']);
        $this->assertStringContainsString('edit_entity', $result['note']);
    }

    // ------------------------------------------------------- an explicit pair

    /**
     * Refused for the right reason, which is the whole point of the check.
     *
     * A live ad is kept out of the candidate list, so the pre-existing
     * ownership check would already refuse it - but as "does not belong to this
     * campaign", which is untrue and sends the model looking for a better id.
     * It does belong; it is merely live. The campaign keeps a draft here so the
     * refusal happens inside the mapping rather than at the front door.
     */
    public function test_a_mapping_naming_a_live_ad_is_refused_as_live_not_as_unknown(): void
    {
        $campaign = $this->campaign();
        $old = $this->asset('assets/old.png');
        $new = $this->asset('assets/new.png');

        $live = $this->ad($campaign, externalId: 'ad-1', assetId: $old->id);

        $this->ad($campaign);

        $result = $this->attach(['mapping' => [['ad_id' => $live->id, 'asset_id' => $new->id]]]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('already live', $result['error']);
        $this->assertStringNotContainsString('does not belong', $result['error']);
        $this->assertStringContainsString('edit_entity', $result['note']);
        $this->assertSame($old->id, $live->fresh()->asset_id);
    }

    /** Nothing is written at all, even the pairs that were fine on their own. */
    public function test_a_refused_pair_leaves_the_rest_of_the_mapping_unwritten(): void
    {
        $campaign = $this->campaign();
        $asset = $this->asset();

        $draft = $this->ad($campaign);
        $second = $this->ad($campaign);
        $live = $this->ad($campaign, externalId: 'ad-1');

        $result = $this->attach(['mapping' => [
            ['ad_id' => $draft->id, 'asset_id' => $asset->id],
            ['ad_id' => $live->id, 'asset_id' => $asset->id],
        ]]);

        $this->assertStringContainsString('already live', $result['error']);
        $this->assertNull($draft->fresh()->asset_id, 'the first pair was written before the second was refused');
        $this->assertNull($second->fresh()->asset_id);
    }

    /** A mapping of drafts only behaves exactly as it did. */
    public function test_a_mapping_of_drafts_is_applied(): void
    {
        $campaign = $this->campaign();
        $asset = $this->asset();

        $draft = $this->ad($campaign);

        $result = $this->attach(['mapping' => [['ad_id' => $draft->id, 'asset_id' => $asset->id]]]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame($asset->id, $draft->fresh()->asset_id);
    }

    // ------------------------------------------------------- nothing to do

    /** With only live ads there is no half-measure to report as success. */
    public function test_a_fully_live_campaign_is_refused_and_points_at_edit_entity(): void
    {
        $campaign = $this->campaign();
        $old = $this->asset('assets/old.png');
        $this->asset('assets/new.png');

        $live = $this->ad($campaign, externalId: 'ad-1', assetId: $old->id);

        $result = $this->attach();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('already live', $result['error']);
        $this->assertSame(['ad-1'], $result['live_ads']);
        $this->assertStringContainsString('edit_entity', $result['note']);
        $this->assertSame($old->id, $live->fresh()->asset_id);
    }

    /** A campaign with no ads still asks for the copy, not for creatives. */
    public function test_no_ads_still_asks_for_the_copy_first(): void
    {
        $this->campaign();
        $this->asset();

        $result = $this->attach();

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

    /** A draft campaign is untouched by any of this. */
    public function test_a_draft_campaign_has_every_ad_filled(): void
    {
        $campaign = $this->campaign();
        $campaign->forceFill(['status' => 'draft', 'external_campaign_id' => null])->save();

        $asset = $this->asset();

        $one = $this->ad($campaign);
        $two = $this->ad($campaign);

        $result = $this->attach();

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame($asset->id, $one->fresh()->asset_id);
        $this->assertSame($asset->id, $two->fresh()->asset_id);
        $this->assertArrayNotHasKey('left_alone_because_they_are_live', $result);
    }
}
