<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Briefs;
use App\DTOs\LandingPageAnalysis;
use App\Models\ArtifactFieldSource;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\User;
use App\Services\LandingPageAnalyzer;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request;
use Mockery;
use Tests\TestCase;

/**
 * Reading a second product's page must not rewrite the first product's campaign.
 *
 * Found on the dev server on 5 Oct, testing the multi-brief work end to end. A
 * second thing to advertise was described in a chat that already had a draft.
 * The page was read first, as it always is, and three things went to the wrong
 * place at once:
 *
 *   - the brief's landing_url, because current() follows focus and focus was
 *     still on the first campaign
 *   - the first campaign's own landing_url, written beside it
 *   - the first campaign's name, because renamePlaceholders() walked every
 *     draft campaign in the conversation
 *
 * The second intent was then created with no landing page at all, and the first
 * campaign pointed at a product it was not advertising and was named after it.
 *
 * Focus is the thing that cannot help here: it cannot move to the new campaign
 * until the new campaign exists, and the page is read before that. So the tool
 * is told, and Briefs holds the new intent for the turn.
 */
class ANewIntentsPageDoesNotOverwriteTheOldOneTest extends TestCase
{
    use RefreshDatabase;

    private const FIRST = 'https://example.com/mens-wool-runner';

    private const SECOND = 'https://example.com/womens-tree-runner';

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

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

        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-new-intent-page');
        $workspace->ownedBy(auth()->user());

        $this->fakeAnalyzer();
    }

    /** The analyser answers from the URL, so each page has its own name. */
    private function fakeAnalyzer(): void
    {
        $analyzer = Mockery::mock(LandingPageAnalyzer::class);

        $analyzer->shouldReceive('analyze')->andReturnUsing(function (string $url): LandingPageAnalysis {
            $name = str_contains($url, 'tree') ? 'Tree Runners' : 'Wool Runners';

            return new LandingPageAnalysis(
                url: $url,
                title: $name.' - Allbirds',
                description: 'Shoes made from natural materials.',
                // campaignName() reads the first heading, so this is what a
                // renamed campaign ends up called.
                headings: [$name],
                text: 'Wear-all-day comfort.',
                keywords: ['shoes'],
            );
        });

        $this->app->instance(LandingPageAnalyzer::class, $analyzer);
    }

    private function tool(string $name): object
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t) => $t->name() === 'campaign__'.$name);

        $this->assertNotNull($tool, "{$name} is not registered.");

        return $tool;
    }

    /** @return array<string, mixed> */
    private function analyze(string $url, bool $newIntent = false): array
    {
        return json_decode((string) $this->tool('analyze_landing_page')->handle(new Request(array_filter([
            'url' => $url,
            'new_intent' => $newIntent ?: null,
        ]))), true);
    }

    /** @return array<string, mixed> */
    private function start(string $name, bool $newIntent = false): array
    {
        return json_decode((string) $this->tool('start_campaign')->handle(new Request(array_filter([
            'platforms' => ['meta'],
            'name' => $name,
            'new_intent' => $newIntent ?: null,
        ]))), true);
    }

    /**
     * The first thing being advertised, built the ordinary way.
     *
     * Started before its page is read, so it is named from the page rather than
     * by the buyer. That is what the campaign on dev looked like - created as
     * "Meta campaign 5 Oct 12:20", renamed once the page was read - and it is
     * the only shape renamePlaceholders() will touch at all. Naming it here
     * instead would make every rename assertion below pass on the provenance
     * check without the scoping ever being exercised.
     */
    private function firstIntent(): Campaign
    {
        $this->start('');
        $this->analyze(self::FIRST);
        app(Briefs::class)->settle();

        return Campaign::where('platform', 'meta')->firstOrFail();
    }

    public function test_the_first_campaign_keeps_its_own_landing_page(): void
    {
        $first = $this->firstIntent();

        $this->analyze(self::SECOND, newIntent: true);
        $this->start('Tree Runners', newIntent: true);

        $this->assertSame(
            self::FIRST,
            $first->fresh()->landing_url,
            'the first campaign was pointed at the second product\'s page',
        );
    }

    /** And its brief does too. */
    public function test_the_first_brief_keeps_its_own_landing_page(): void
    {
        $first = $this->firstIntent();

        $this->analyze(self::SECOND, newIntent: true);
        $this->start('Tree Runners', newIntent: true);

        $this->assertSame(self::FIRST, Brief::findOrFail($first->brief_id)->landing_url);
    }

    /**
     * The new intent gets the page, which is the half that was simply lost.
     *
     * On dev the second brief was created with landing_url null, so the campaign
     * the user had just asked for had no destination at all.
     */
    public function test_the_new_intent_gets_the_page_it_was_read_for(): void
    {
        $first = $this->firstIntent();

        $this->analyze(self::SECOND, newIntent: true);
        $this->start('Tree Runners', newIntent: true);

        $second = Campaign::where('id', '!=', $first->id)->firstOrFail();

        $this->assertNotSame($first->fresh()->brief_id, $second->brief_id, 'precondition: separate briefs');
        $this->assertSame(self::SECOND, Brief::findOrFail($second->brief_id)->landing_url);
        $this->assertSame(self::SECOND, $second->landing_url);
    }

    /**
     * The first campaign is not renamed after the other product's page.
     *
     * Its name came from its own page, so the provenance is MODEL_INFERRED and
     * renamePlaceholders() is willing to overwrite it. Only the scoping to the
     * brief being read stops it, which is what this asserts.
     */
    public function test_the_first_campaign_is_not_renamed(): void
    {
        $first = $this->firstIntent();
        $before = $first->name;

        $this->assertStringContainsString('wool-runners', $before, 'precondition: named from its own page');

        $this->analyze(self::SECOND, newIntent: true);

        $this->assertSame($before, $first->fresh()->name, 'it was renamed after a page it does not point at');
        $this->assertStringNotContainsString('tree-runners', $first->fresh()->name);
    }

    /**
     * A placeholder name on the intent being read is still replaced.
     *
     * The behaviour renamePlaceholders() exists for: a campaign created before
     * the page was read is carrying a generated name, and the page is where its
     * real one comes from.
     */
    public function test_a_placeholder_on_the_intent_being_read_is_still_replaced(): void
    {
        $this->start('');
        $campaign = Campaign::where('platform', 'meta')->firstOrFail();
        app(Workspace::class)->recordSource($campaign, 'name', ArtifactFieldSource::FALLBACK);

        $this->analyze(self::FIRST);

        $this->assertStringContainsString('wool-runners', $campaign->fresh()->name);
    }

    /**
     * Without the flag nothing changes, because that is the ordinary case.
     *
     * Re-reading the page for the campaign in hand must still write to it.
     */
    public function test_without_the_flag_the_page_still_lands_on_the_campaign_in_focus(): void
    {
        $first = $this->firstIntent();

        $this->analyze(self::SECOND);

        $this->assertSame(self::SECOND, $first->fresh()->landing_url);
        $this->assertSame(1, Brief::where('conversation_id', 'conv-new-intent-page')->count());
    }

    /**
     * Reading a page on a first message still works, where there is no brief
     * and no campaign to attach anything to yet.
     */
    public function test_a_first_message_page_is_unaffected(): void
    {
        $this->analyze(self::FIRST, newIntent: true);
        $this->start('Wool Runners', newIntent: true);
        app(Briefs::class)->settle();

        $campaign = Campaign::where('platform', 'meta')->firstOrFail();

        $this->assertSame(self::FIRST, $campaign->landing_url);
        $this->assertSame(
            1,
            Brief::where('conversation_id', 'conv-new-intent-page')->count(),
            'an empty brief was left behind',
        );
    }
}
