<?php

namespace App\Campaigns;

use App\Agent\Workspace;
use App\DTOs\LandingPageAnalysis;
use App\Models\Brief;
use App\Models\Campaign;
use Illuminate\Support\Collection;

/**
 * The brief belonging to the intent in hand.
 *
 * One per intent, not one per conversation: a brief is one thing being
 * advertised, which may run on several platforms, and a chat holds as many of
 * those as the buyer has. Nothing asks the user to start one - it appears when
 * the landing page is read, which is the first question anyway - and
 * start_campaign mints the next when a second thing is being advertised.
 *
 * Which of them is current() follows focus, because that is what already tracks
 * the campaign the buyer is working on.
 *
 * Kept out of the tools so none of them has to know how a brief comes into
 * being, and so the rule lives in one place rather than being re-implemented
 * wherever a tool needs one.
 */
class Briefs
{
    /**
     * An analysis recorded before there was a brief to put it on.
     *
     * The first message of a new chat runs its whole turn before the
     * conversation exists, which the Workspace documents and handles the same
     * way for artifacts. Without this the landing page read on that turn is
     * dropped, and it is the one turn that always carries it.
     */
    private ?LandingPageAnalysis $pending = null;

    /**
     * Campaigns created before there was a brief to put them on.
     *
     * Same problem as $pending and the same turn: start_campaign runs while the
     * conversation still does not exist, so current() has nothing to key on and
     * correctly declines to invent a brief. The campaigns are created anyway,
     * because refusing to create them would be worse, and they are remembered
     * here so settle() can finish the job.
     *
     * @var list<int>
     */
    private array $orphans = [];

    /**
     * A total named before there was a brief to put it on.
     *
     * @var array{budget: float, budget_mode: ?string}|null
     */
    private ?array $pendingTotal = null;

    /**
     * A new intent begun this turn, before anything is focused on it.
     *
     * Focus is what current() normally follows, and focus cannot move until a
     * campaign exists to move it to. So everything between "the user described
     * a different thing" and start_campaign creating it still resolves to the
     * previous intent's brief.
     *
     * Found on the dev server on 5 Oct. A second product's landing page was
     * analysed while the first campaign was still in focus: the URL and the
     * page's name were written onto the first intent's brief and campaign, and
     * the second intent was then created with no landing page at all. The first
     * campaign was renamed after a product it was not advertising.
     *
     * Held for the turn, like $pending above and for the same reason. The next
     * turn has a campaign to focus and does not need it.
     */
    private ?Brief $intentInProgress = null;

    public function __construct(private readonly Workspace $workspace) {}

    /** Remember a campaign that was created with no brief to join. */
    public function orphaned(Campaign $campaign): void
    {
        $this->orphans[] = $campaign->id;
    }

    /**
     * How many distinct platforms this brief will cover once it has settled.
     *
     * The campaigns already attached, plus the ones created this turn that are
     * waiting for settle() to attach them. Asking the brief alone is right from
     * the second message on and wrong during the first, when nothing is
     * attached yet: that is how "advertise this on Meta and Google, 20 a day
     * total" came to write the whole 20 to whichever campaign was in focus.
     *
     * Deliberately the brief's campaigns rather than the conversation's. Two
     * campaigns that do not share a brief do not share a budget either, and
     * counting everything in the conversation would turn "make that one 12 a
     * day" into a total the moment a second campaign existed.
     */
    /**
     * Every campaign this brief covers, one per platform.
     *
     * Includes the ones the first message created before there was a brief to
     * attach them to, which is the whole reason orphans are tracked. Callers
     * that need the campaigns rather than the number must come through here:
     * counting the brief's own relation instead returns 1 during the first
     * turn, and a caller that mixed the two decided a budget was being split
     * across two platforms and then divided it by one.
     *
     * @return Collection<int, Campaign>
     */
    public function sharedCampaigns(): Collection
    {
        $attached = $this->current()?->campaigns()->get() ?? collect();

        return $attached
            ->merge(Campaign::query()->whereIn('id', $this->orphans)->get())
            ->filter(fn (Campaign $campaign): bool => filled($campaign->platform))
            ->unique('platform')
            ->values();
    }

    public function sharedPlatforms(): int
    {
        return $this->sharedCampaigns()->count();
    }

    /**
     * Finish what the first message could not.
     *
     * Called once the conversation exists, which on a new chat is only after
     * the turn has run. Everything before this point had nowhere to write: the
     * page analysis was held, and any campaign created in the same turn was
     * left without a brief.
     *
     * Found on the dev server on 23 Sep. Saying "advertise this on Meta and
     * Google" in one message produced two campaigns and no brief at all, so the
     * landing page, the money and the dates were shared by nothing and every
     * question would have been asked twice.
     *
     * Only the campaigns this instance created are adopted, by id. Sweeping up
     * everything brief-less in the conversation would pull in campaigns from
     * earlier turns and adopted ones from the platform, none of which were made
     * from this brief.
     */
    public function settle(): void
    {
        if ($this->pending === null && $this->pendingTotal === null && $this->orphans === []) {
            return;
        }

        $brief = $this->current();

        if ($brief === null) {
            return;
        }

        // current() already flushed $pending. What is left is the adoption.
        if ($this->orphans !== []) {
            Campaign::query()
                ->whereIn('id', $this->orphans)
                ->whereNull('brief_id')
                ->update(['brief_id' => $brief->id]);

            $this->orphans = [];
        }
    }

    /**
     * Keep what the landing page said, now or as soon as there is somewhere.
     *
     * Returns whether it was written. False means it is held and will be
     * flushed by the next current() once the conversation exists.
     */
    public function remember(LandingPageAnalysis $analysis): bool
    {
        if ($brief = $this->current()) {
            $brief->rememberPageAnalysis($analysis);

            return true;
        }

        $this->pending = $analysis;

        return false;
    }

    /**
     * Keep the total to be divided, now or as soon as there is somewhere.
     *
     * The same holding pattern as remember() above, for the same reason. A
     * budget named in the first message has no brief to land on: "advertise
     * this on Meta and Google, 20 a day total" arrives while the conversation
     * still does not exist, and on dev the 20 went to whichever campaign was in
     * focus while the other platform got nothing and split_budget had no total
     * to divide.
     *
     * Returns whether it was written. False means it is held for settle().
     */
    public function rememberTotal(float $budget, ?string $mode = null): bool
    {
        if ($brief = $this->current()) {
            $brief->update(array_filter([
                'budget' => $budget,
                'budget_mode' => $mode,
            ], fn (mixed $value): bool => $value !== null));

            return true;
        }

        $this->pendingTotal = ['budget' => $budget, 'budget_mode' => $mode];

        return false;
    }

    /**
     * The conversation's brief, or null when there is no conversation to hang
     * one on - a tool called outside a chat, which happens in tests and in the
     * controller's own step-in calls.
     */
    public function current(): ?Brief
    {
        $conversation = $this->workspace->id();

        // The workspace knows the owner in a chat; auth does outside one, which
        // is how a tool called directly still gets the right brief. With
        // neither there is nobody to own it, and a brief nobody owns is not
        // something to invent - the caller carries on without one.
        $owner = $this->workspace->owner()?->getKey() ?? auth()->id();

        if (blank($conversation) || blank($owner)) {
            return null;
        }

        // Keyed by owner as well as conversation, deliberately. Keying on the
        // conversation alone means anything that binds a workspace without
        // checking who owns the conversation hands back somebody else's brief,
        // with their landing page, budget and page analysis in it. Every path
        // does check today; this makes it impossible rather than conventional.
        // A new intent begun this turn beats focus, because focus is still on
        // the thing it is not. Nothing else in the turn can distinguish them.
        if ($this->intentInProgress !== null) {
            return $this->flushInto($this->intentInProgress);
        }

        // The brief of whatever is in focus, when that is a campaign we made.
        //
        // A conversation holds one brief per intent now rather than one brief
        // full stop, so "the conversation's brief" stopped being a question
        // with a single answer. Focus is the one thing that already tracks what
        // the buyer is working on: the panel switches it, open_campaign moves
        // it, and the twenty-nine tools that act on a campaign all read it. A
        // brief that followed anything else would disagree with the campaign on
        // screen, and these callers use it to answer questions about that
        // campaign - its objective, its targeting, its dates.
        //
        // A campaign adopted from the platform has no brief and must not be
        // given somebody else's, so this only follows the link when there is
        // one.
        $focused = $this->workspace->focus();

        if ($focused instanceof Campaign && $focused->brief !== null) {
            return $this->flushInto($focused->brief);
        }

        // Otherwise the newest, which is the one being filled in. firstOrCreate
        // would hand back the oldest and quietly write a second intent's
        // answers onto the first one's brief.
        $brief = Brief::query()
            ->where(['conversation_id' => $conversation, 'user_id' => $owner])
            ->latest('id')
            ->first()
            ?? Brief::query()->create(['conversation_id' => $conversation, 'user_id' => $owner]);

        return $this->flushInto($brief);
    }

    /**
     * Start a second intent in the same conversation.
     *
     * A brief is one thing being advertised, which may run on several
     * platforms; a conversation is as many of those as the buyer wants. This
     * mints the next one rather than reusing the brief already holding
     * campaigns, because the two have different landing pages, different dates
     * and different money.
     *
     * The money is the reason this is a new row rather than a shared one.
     * budget is in ResolvesFromBrief::SHARED_WITH_BRIEF, so a campaign with no
     * budget of its own reads the brief's total: two intents on one brief, one
     * of them unbudgeted, and both spend the whole amount. needsBudgetSplit()
     * would not catch it either, because platforms() dedupes and two campaigns
     * on the same platform read as one.
     */
    /**
     * Begin a different thing to advertise, before it has a campaign.
     *
     * For the tools that run ahead of start_campaign - reading the landing page
     * above all - so that what they record lands on the new intent rather than
     * on whatever is still in focus.
     *
     * Reuses the brief in hand when it holds no campaigns, because that is an
     * intent nobody has built yet rather than a previous one: a new chat's first
     * brief, or a second intent already begun earlier in this same turn. Minting
     * regardless would leave an empty brief behind on every call and would make
     * the order of two tools in one turn decide how many briefs appear.
     *
     * Distinct from startNew(), which always mints: start_campaign calls that
     * when it has already decided this call is a separate campaign, and its
     * decision must not be undone by an empty brief happening to be current.
     */
    public function beginNewIntent(): ?Brief
    {
        if ($this->intentInProgress !== null) {
            return $this->intentInProgress;
        }

        $current = $this->current();

        if ($current !== null && ! $current->campaigns()->exists()) {
            return $this->intentInProgress = $current;
        }

        return $this->intentInProgress = $this->startNew();
    }

    public function startNew(): ?Brief
    {
        $conversation = $this->workspace->id();
        $owner = $this->workspace->owner()?->getKey() ?? auth()->id();

        if (blank($conversation) || blank($owner)) {
            return null;
        }

        return $this->flushInto(
            Brief::query()->create(['conversation_id' => $conversation, 'user_id' => $owner]),
        );
    }

    /** Anything recorded before there was a brief to put it on belongs to this one. */
    private function flushInto(Brief $brief): Brief
    {
        if ($this->pending !== null) {
            $brief->rememberPageAnalysis($this->pending);
            $this->pending = null;
        }

        if ($this->pendingTotal !== null) {
            $brief->update(array_filter(
                $this->pendingTotal,
                fn (mixed $value): bool => $value !== null,
            ));
            $this->pendingTotal = null;
        }

        return $brief;
    }

    /**
     * Attach a campaign to the conversation's brief, if it has none.
     *
     * Never reassigns: a campaign that already belongs to a brief keeps it, and
     * an adopted campaign pulled in from the platform is left alone entirely
     * unless something deliberately gives it one.
     */
    public function attach(Campaign $campaign): ?Brief
    {
        $brief = $this->current();

        if ($brief === null) {
            return null;
        }

        if ($campaign->brief_id === null) {
            $campaign->update(['brief_id' => $brief->id]);
        }

        return $brief;
    }
}
