<?php

namespace Tests\Feature;

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

/**
 * A conversation holds as many intents as the buyer has.
 *
 * A brief is one thing being advertised, which may run on several platforms. A
 * conversation used to hold exactly one, so the second thing somebody wanted to
 * advertise in the same chat was given no brief at all. That kept the money
 * apart and cost everything else: with nowhere to hold a landing page, dates or
 * a total, the second intent could not fan out across platforms the way the
 * first one could, and every shared answer was asked again.
 *
 * Now it gets its own brief. Same isolation, expressed as a separate row rather
 * than an absent one, which is also what lets a second campaign exist on a
 * platform that already has a published one.
 *
 * Three ways a call can relate to what is already in the conversation, and all
 * three are decided before any campaign is touched:
 *
 *   - a draft already on a platform asked for -> a re-entry, update that draft
 *   - a published campaign there -> a second intent, which cannot be an edit
 *   - no overlap at all -> ambiguous, so the model says via same_brief
 */
class ManyBriefsInOneConversationTest extends TestCase
{
    use RefreshDatabase;

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

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

        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-many-briefs');
        $workspace->ownedBy(auth()->user());
    }

    /**
     * @param  list<string>  $platforms
     * @return array<string, mixed>
     */
    private function start(
        array $platforms,
        ?string $name = null,
        bool $sameBrief = false,
        bool $newIntent = false,
    ): array {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t) => $t->name() === 'campaign__start_campaign');

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

        return json_decode((string) $tool->handle(new Request(array_filter([
            'platforms' => $platforms,
            'name' => $name,
            'same_brief' => $sameBrief ?: null,
            'new_intent' => $newIntent ?: null,
        ]))), true);
    }

    private function campaignOn(string $platform, int $briefId): ?Campaign
    {
        return Campaign::where('platform', $platform)->where('brief_id', $briefId)->first();
    }

    private function briefsHere(): int
    {
        return Brief::where('conversation_id', 'conv-many-briefs')->count();
    }

    public function test_a_second_thing_to_advertise_gets_its_own_brief(): void
    {
        $this->start(['meta'], 'Running shoes');
        app(Briefs::class)->settle();

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

        $this->start(['google'], 'Handbags');

        $this->assertSame(2, $this->briefsHere(), 'Two intents should mean two briefs.');

        $second = Campaign::where('platform', 'google')->firstOrFail();

        $this->assertNotNull($second->brief_id, 'The second intent should have a brief of its own.');
        $this->assertNotSame($first->fresh()->brief_id, $second->brief_id);
    }

    /**
     * The capability this unlocks, and the reason an absent brief was not enough.
     *
     * One intent, several platforms, is what a brief is for. The second intent
     * could not do it while it had no brief to hold the shared answers.
     */
    public function test_the_second_intent_fans_out_across_platforms_like_the_first(): void
    {
        $this->start(['meta'], 'Running shoes');
        app(Briefs::class)->settle();

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

        // A different thing to advertise, in two places at once.
        $this->start(['google', 'linkedin'], 'Handbags');

        $secondBrief = Brief::where('conversation_id', 'conv-many-briefs')
            ->where('id', '!=', $firstBrief)
            ->value('id');

        $this->assertNotNull($secondBrief);
        $this->assertNotNull($this->campaignOn('google', $secondBrief), 'The second intent needs its own Google campaign.');
        $this->assertNotNull($this->campaignOn('linkedin', $secondBrief), 'And its own LinkedIn campaign.');
    }

    /**
     * No money crosses between intents.
     *
     * budget is in ResolvesFromBrief::SHARED_WITH_BRIEF, so a campaign with
     * none of its own reads its brief's total. Two intents sharing one brief
     * would therefore both spend the whole amount, and needsBudgetSplit() would
     * not notice because platforms() dedupes and two campaigns on the same
     * platform read as one.
     */
    public function test_the_second_intent_does_not_inherit_the_first_briefs_budget(): void
    {
        $this->start(['meta'], 'Running shoes');
        app(Briefs::class)->settle();

        $first = Campaign::where('platform', 'meta')->firstOrFail();
        Brief::whereKey($first->brief_id)->update(['budget' => 500, 'budget_mode' => 'daily']);

        $this->start(['google'], 'Handbags');

        $second = Campaign::where('platform', 'google')->firstOrFail();

        $this->assertNotSame($first->fresh()->brief_id, $second->brief_id, 'Precondition: separate briefs.');
        $this->assertNull(
            $second->fresh()->budget,
            'The second intent inherited the first one\'s money.',
        );
    }

    /**
     * A second thing to advertise on a platform that already has a draft.
     *
     * The commonest shape of all, and the one a draft clash cannot infer: "a
     * second Meta campaign for a different product" and "change the Meta
     * campaign I am building" arrive as the same call with the same arguments.
     * Re-entry is the right default, so the new thing has to say so.
     *
     * Found on the dev server on 5 Oct rather than here, because every test
     * above reaches a second intent by changing platform or by publishing
     * first. start_campaign returned the first campaign's id, and the model
     * refused to apply the new budget rather than overwrite the first one's -
     * which is the right instinct and not a substitute for being able to do it.
     */
    public function test_a_second_intent_on_a_platform_with_a_draft_is_possible(): void
    {
        $this->start(['meta'], 'Running shoes');
        app(Briefs::class)->settle();

        $first = Campaign::where('platform', 'meta')->firstOrFail();
        Brief::whereKey($first->brief_id)->update(['budget' => 20, 'budget_mode' => 'daily']);

        $result = $this->start(['meta'], 'Handbags', newIntent: true);

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

        $this->assertNotNull($second, 'the second thing to advertise reused the first campaign');
        $this->assertNotSame(
            (int) $first->id,
            (int) ($result['campaign_id'] ?? 0),
            'the call answered with the first campaign\'s id',
        );
        $this->assertNotSame($first->fresh()->brief_id, $second->brief_id);
        $this->assertNull($second->fresh()->brief->budget, 'it inherited the first intent\'s money');
        $this->assertSame('Handbags', $second->name);
        $this->assertSame('Running shoes', $first->fresh()->name, 'the first campaign was renamed');
    }

    /** And without it, the same call still means "go back to that draft". */
    public function test_without_the_signal_a_draft_clash_is_still_a_re_entry(): void
    {
        $this->start(['meta'], 'Running shoes');
        app(Briefs::class)->settle();

        $this->start(['meta'], 'A better name');

        $this->assertSame(1, Campaign::where('platform', 'meta')->count());
        $this->assertSame(1, $this->briefsHere());
    }

    /**
     * A second campaign on a platform that already has a published one.
     *
     * This is the case the product used to refuse outright, because there was
     * nowhere for the second campaign to live: sharing the first one's brief
     * would have shared its budget, and the conversation could hold only one
     * brief. It can hold two now, so the campaign is made instead of refused.
     *
     * A draft on that platform still means a re-entry rather than a second
     * intent, which is the next test. Published is the thing that makes it
     * unambiguous: a published campaign cannot be the draft being worked on.
     */
    public function test_a_second_campaign_is_created_beside_a_published_one(): void
    {
        $this->start(['meta'], 'Running shoees');
        app(Briefs::class)->settle();

        $live = Campaign::where('platform', 'meta')->firstOrFail();
        $live->update(['status' => 'published', 'external_campaign_id' => '120250886412960429']);
        $liveName = $live->name;

        $result = $this->start(['meta'], 'Running shoes');

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? '');

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

        $this->assertNotNull($second, 'A second Meta campaign should be created, not refused.');
        $this->assertNotSame($live->brief_id, $second->brief_id, 'It must not share the published campaign\'s brief.');

        // The whole point of the old refusal, still guaranteed.
        $this->assertSame($liveName, $live->fresh()->name, 'The published campaign was renamed.');
        $this->assertSame('published', $live->fresh()->status);
    }

    /**
     * Re-entering the flow on a draft still updates it rather than duplicating.
     *
     * The ordinary case, and the reason a draft clash is not treated as a second
     * intent: the agent calls start_campaign again while building the same
     * campaign, and a second draft beside the first would be a mess nobody
     * asked for.
     */
    public function test_a_draft_on_the_same_platform_is_updated_not_duplicated(): void
    {
        $this->start(['meta'], 'Working title');
        app(Briefs::class)->settle();

        $this->start(['meta'], 'A better name');

        $this->assertSame(1, Campaign::where('platform', 'meta')->count(), 'The draft was duplicated.');
        $this->assertSame('A better name', Campaign::where('platform', 'meta')->firstOrFail()->name);
        $this->assertSame(1, $this->briefsHere(), 'Re-entry should not start a second brief.');
    }

    /**
     * "Also run it on Google" joins the intent in hand instead of splitting it.
     *
     * With no platform overlap, nothing in the call says whether this is another
     * platform for the thing in hand or a new thing entirely: same arguments,
     * same focus, either way. Hence same_brief, which the model sets from the
     * sentence it read. Defaulting the other way is the safe direction - a brief
     * wrongly split costs re-asked questions, a brief wrongly shared spends one
     * budget twice.
     */
    public function test_another_platform_for_the_same_thing_joins_the_brief(): void
    {
        $this->start(['meta'], 'Running shoes');
        app(Briefs::class)->settle();

        $before = Campaign::count();

        $this->start(['google'], 'Running shoes', sameBrief: true);

        $this->assertSame(1, $this->briefsHere(), 'Adding a platform to the intent in hand started a new one.');
        $this->assertSame($before + 1, Campaign::count(), 'It should add the Google campaign to the same brief.');
    }

    /**
     * And same_brief cannot put a second campaign into a published one's brief.
     *
     * The model asserting it does not make it true, and here it would share the
     * published campaign's budget with a brand new campaign. A brief is one
     * thing advertised once per platform, which the rest of the code relies on:
     * sharedCampaigns() dedupes by platform, so a second Meta campaign in the
     * same brief would be invisible to the budget split.
     */
    public function test_the_same_brief_signal_cannot_join_a_published_platform(): void
    {
        $this->start(['meta'], 'Running shoes');
        app(Briefs::class)->settle();

        $live = Campaign::where('platform', 'meta')->firstOrFail();
        $live->update(['status' => 'published', 'external_campaign_id' => '120250886412960429']);

        $this->start(['meta'], 'Handbags', sameBrief: true);

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

        $this->assertNotNull($second, 'A second Meta campaign should still be created.');
        $this->assertNotSame(
            $live->brief_id,
            $second->brief_id,
            'Two campaigns on one platform were put in the same brief.',
        );
    }

    /**
     * Which of a conversation's briefs is "the" brief: the one in focus.
     *
     * Once a conversation holds more than one, every caller that asks Briefs for
     * the current one needs an answer, and focus is the only thing that already
     * tracks which campaign the buyer is working on - the panel sets it,
     * open_campaign moves it, and the tools that edit a campaign all read it.
     *
     * So going back to the first campaign must take its brief with it. Returning
     * the newest instead would write the answers for the campaign on screen onto
     * a different intent's brief, and because budget is shared with the brief,
     * the money would land on the wrong campaigns.
     */
    public function test_the_brief_follows_the_campaign_in_focus(): void
    {
        $this->start(['meta'], 'Running shoes');
        app(Briefs::class)->settle();

        $first = Campaign::where('platform', 'meta')->firstOrFail();
        $firstBrief = $first->brief_id;

        $this->start(['google'], 'Handbags');

        $second = Campaign::where('platform', 'google')->firstOrFail();
        $this->assertNotSame($firstBrief, $second->brief_id, 'Precondition: two briefs.');

        // The buyer goes back to the first campaign, as open_campaign does.
        app(Workspace::class)->focusOn($first);

        $this->assertSame(
            $firstBrief,
            app(Briefs::class)->current()?->id,
            'The brief did not follow focus back to the first campaign.',
        );

        // And a shared answer recorded now lands on that brief, not the newest.
        app(Briefs::class)->rememberTotal(100, 'daily');

        $this->assertSame(100.0, (float) Brief::findOrFail($firstBrief)->budget);
        $this->assertNull(Brief::findOrFail($second->brief_id)->budget, 'The total leaked onto the other intent.');
    }

    /**
     * With nothing in focus, the newest is the one being filled in.
     *
     * This is the path a tool takes before any campaign exists for the intent -
     * analyze_landing_page on the second thing being advertised, for example.
     * firstOrCreate, which is what a single-brief conversation could safely use,
     * hands back the oldest and would quietly write the second intent's landing
     * page and budget onto the first one's brief.
     */
    public function test_with_nothing_in_focus_the_newest_brief_is_the_current_one(): void
    {
        $briefs = app(Briefs::class);

        $oldest = $briefs->current();
        $newest = $briefs->startNew();

        $this->assertNotNull($oldest);
        $this->assertNotSame($oldest->id, $newest?->id, 'Precondition: two briefs, nothing in focus.');

        $this->assertSame($newest->id, $briefs->current()?->id, 'current() went back to the older brief.');
    }
}
