<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Choices;
use App\Agent\Workspace;
use App\Campaigns\Briefs;
use App\Campaigns\Platforms\Platforms;
use App\Models\ArtifactFieldSource;
use App\Models\Brief;
use App\Models\Campaign;
use App\Support\GeneratedNames;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;

/**
 * Create a campaign in this conversation.
 *
 * The worked example for the pattern every module should follow:
 *
 *   1. a plain Tool, no knowledge of the agent or the registry
 *   2. the Workspace injected, so the tool never has to be told the context
 *   3. produced() to link and focus the new artifact in one step
 *   4. recordSource() for every field, so the publish gate can tell a stated
 *      value from a guessed one later
 *
 * A campaign row is created only here, never implicitly when a chat starts.
 * A conversation is a workspace, not a campaign.
 */
class StartCampaign implements Tool
{
    public function __construct(
        private readonly Workspace $workspace,
        private readonly Choices $choices,
        private readonly Platforms $platforms,
        private readonly Briefs $briefs,
    ) {}

    public function description(): Stringable|string
    {
        return 'Create the campaigns for this conversation, one per platform the user picked, '
            .'and put the first in focus. Pass several platforms when the user wants to advertise '
            .'the same thing in more than one place: they share one brief, so the questions that do '
            .'not change by platform are only asked once. '
            .'Call this again for a second, different thing to advertise in the same chat - that is '
            .'supported and it gets its own brief, its own landing page and its own budget - but pass '
            .'new_intent when you do, or a call naming a platform that already has a draft is read as '
            .'going back to that draft. If instead they want the thing already being set up to run '
            .'somewhere else as well, pass same_brief so the answers already given carry over. '
            .'Everything is created as a draft; nothing '
            .'reaches an advertising platform until the user approves it separately. '
            .'Only pass a platform the user has actually named. If they have not said where the ads '
            .'should run, omit it and they will be asked: do not assume Meta, and do not infer a '
            .'platform from the product, the landing page or what happens to be connected.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'name' => $schema->string()
                ->description('Only pass a name explicitly supplied by the user. Otherwise omit it: a descriptive name with user, platform and date tags is generated.'),
            // items() is not optional: Gemini rejects the whole request with a
            // 400 when an array parameter does not say what it contains, and
            // the tool schema is sent on every turn, so one bad declaration
            // stops the entire chat rather than just this tool.
            'platforms' => $schema->array()->items($schema->string())
                ->description('The platforms the user named, for example ["meta","google"]. Omit whenever they '
                    .'have not said where the ads should run, which puts the choice on screen for them to pick.'),
            'platform' => $schema->string()
                ->description('A single platform, when the user named exactly one. Same as passing one entry in platforms.'),
            'objective' => $schema->string()
                ->description('The campaign objective, if the user has stated or implied one.'),
            // Asked of the model because nothing here can work it out. "Also run
            // it on Google" and "now advertise the handbags on Google" arrive as
            // the same call with the same arguments, from the same focus, and
            // the only difference is the sentence - which only the model has
            // read. Guessing wrong in the unsafe direction makes two unrelated
            // campaigns share a budget, so this defaults to a separate brief.
            'same_brief' => $schema->boolean()
                ->description('True only when this is another platform for the thing already being '
                    .'set up in this conversation, for example "also run it on Google". It then shares '
                    .'that campaign\'s brief, so the landing page, budget and dates carry over and are '
                    .'not asked again. Omit for a new thing being advertised, even in the same chat: '
                    .'it gets its own brief and its own budget.'),
            // The opposite signal, and it needs saying separately.
            //
            // Calling this again for a platform that already has a draft is
            // read as going back to that draft, because re-entering the flow on
            // the campaign in hand is far commoner than starting a second one
            // beside it. That default is right and it has no exception the
            // arguments can imply: "another Meta campaign, different product"
            // and "change the Meta campaign I am building" arrive identically.
            //
            // Found on the dev server on 5 Oct. Asked for a second Meta
            // campaign for a different product while the first was still a
            // draft, start_campaign returned the first campaign's id, and the
            // model noticed and refused to apply the new budget rather than
            // overwrite the first one's.
            'new_intent' => $schema->boolean()
                ->description('True when the user is starting a different thing to advertise, rather '
                    .'than changing the campaign already being built. Needed whenever that new thing '
                    .'runs on a platform this conversation already has a draft for, because otherwise '
                    .'this call is read as going back to that draft. It gets its own campaign, its own '
                    .'brief and its own budget. Do not set it when they are correcting or adding to the '
                    .'campaign in hand.'),
        ];
    }

    /** Include ownership and creation tags in generated names; preserve explicit names. */
    private function nameFor(?string $given, string $platform, ?Brief $brief): string
    {
        $given = trim((string) $given);

        if ($given !== '') {
            return $given;
        }

        $fromPage = trim((string) ($brief?->pageAnalysis()?->campaignName() ?? ''));

        return GeneratedNames::campaign($fromPage, $platform, auth()->user());
    }

    /**
     * The objective, but only if this platform has it.
     *
     * It was written straight to the column with no check, so a Meta objective
     * landed on a Google or LinkedIn campaign: nine refusals across the stored
     * conversations, all of them "[OUTCOME_TRAFFIC] is not supported on Google
     * Ads" arriving a step or two later. Worse than the refusal is what it did
     * to the flow - LaunchFlow::done() only asks whether the field is filled,
     * so the objective step was marked answered and never re-asked, and for
     * Google that also dropped the pixel and conversion event steps, which are
     * gated on an objective the platform does not have. The campaign was then
     * built to the end and refused at the gate.
     *
     * Dropped rather than mapped. Guessing that a Meta traffic objective means
     * Google's WEBSITE_TRAFFIC is a decision about someone's money, and leaving
     * it unset asks the buyer instead, which is the step that already exists.
     */
    private function objectiveForPlatform(?string $objective, string $platform): ?string
    {
        if (blank($objective)) {
            return null;
        }

        $objective = strtoupper(trim((string) $objective));
        $supported = app(Platforms::class)->for($platform)->objectives();

        $supported = array_map(
            fn (mixed $entry): string => strtoupper((string) (is_array($entry) ? ($entry['value'] ?? '') : $entry)),
            $supported,
        );

        return in_array($objective, $supported, true) ? $objective : null;
    }

    public function handle(Request $request): Stringable|string
    {
        // Read through all(): the Request's offsetGet raises on a missing key,
        // and optional arguments are simply absent rather than null.
        $arguments = $request->all();
        $objective = $arguments['objective'] ?? null;

        $chosen = $this->platformsFrom($arguments);

        // The first question of all, and it was the last one still asked in
        // prose. Nothing is in focus yet, so the launch flow cannot offer it:
        // it has to be offered here or not at all.
        if ($chosen === []) {
            $this->offerPlatforms();

            return $this->json([
                'ok' => true,
                'note' => 'The platforms are on screen for the user to pick, and more than one can be '
                    .'chosen. Say one short line and wait. Do not ask for a campaign name: one is generated.',
            ]);
        }

        $supported = $this->platforms->keys();
        $unknown = array_values(array_diff($chosen, $supported));

        if ($unknown !== []) {
            return $this->json([
                'ok' => false,
                'error' => '['.implode(', ', $unknown).'] is not a platform this product supports.',
                'supported' => $supported,
            ]);
        }

        // A brief covers one thing being advertised, on however many platforms.
        //
        // A second, unrelated campaign later in the same conversation is a
        // different thing, and it gets a brief of its own rather than joining
        // this one: budget falls back to the brief, so sharing would have two
        // unrelated campaigns spending the same money.
        //
        // It used to get no brief at all, which kept the money apart and cost
        // everything else - nowhere to hold a landing page, dates or a total, so
        // it could not fan out across platforms the way the first one could, and
        // every shared question was asked again. A separate row is the same
        // isolation without any of that.
        //
        // One reason remains for having no brief here, and it needs the opposite
        // treatment: null means the conversation does not exist yet, on the
        // first message of a new chat, and the campaign must join a brief as
        // soon as there is one. That is what the orphan record below is for.
        $brief = $this->briefs->current();

        // What the intent in hand already has.
        //
        // Its brief's campaigns, scoped to the brief rather than to the
        // conversation. This read every campaign in the conversation, so once a
        // second intent existed, the platform lookup below found the first
        // intent's Meta campaign and either refused or edited it. The question
        // being asked is "does this intent already have a campaign here", and
        // that belongs to the brief.
        //
        // Plus the campaign in focus when it is on no brief at all: one adopted
        // from the platform, or one created on a first message before there was
        // a brief to attach it to. Those are still the thing in hand, and a
        // brief-less campaign cannot belong to a different intent, so leaving
        // them out would make a duplicate beside them.
        $existing = $brief !== null ? $brief->campaigns()->get() : collect();
        $focused = $this->workspace->focus();

        if ($focused instanceof Campaign && $focused->brief_id === null) {
            $existing->push($focused);
        }

        $clash = $existing->whereIn('platform', $chosen);

        // Is this the thing already being set up, or a new one?
        //
        // A draft on a platform asked for settles it: this is a re-entry into
        // the intent in hand and must update that draft rather than make a
        // second campaign beside it. A published campaign settles it the other
        // way, because a published campaign cannot be re-entered - asking again
        // there is a real second campaign.
        //
        // With no overlap at all, nothing in the call distinguishes "also run it
        // on Google" from "now advertise the handbags on Google", so the model
        // is asked. It defaults to a new intent, which is the safe direction:
        // the cost of splitting wrongly is questions asked twice, the cost of
        // sharing wrongly is two campaigns spending one budget.
        //
        // The clash arm comes first and nothing may short-circuit past it. The
        // campaign in focus can be a published one on no brief at all, and then
        // every other arm is satisfied - there is no brief holding campaigns to
        // be a second intent of - so reaching the update branch below with a
        // live campaign is one reordering away.
        $isTheThingInHand = match (true) {
            // Said outright, and it wins. Nothing else here can tell a second
            // thing to advertise from a correction to the first when both run
            // on a platform this conversation already has a draft for.
            (bool) ($arguments['new_intent'] ?? false) => false,
            $clash->isNotEmpty() => $clash->every(fn (Campaign $c): bool => ! $c->isPublished()),
            $brief === null => true,
            default => (bool) ($arguments['same_brief'] ?? false),
        };

        if (! $isTheThingInHand) {
            // Only when there is something to be separate from. A brief holding
            // no campaigns is already a fresh one - which is every first
            // campaign, because current() makes the brief a moment earlier -
            // and minting another would abandon it empty.
            if ($brief->campaigns()->exists()) {
                $brief = $this->briefs->startNew() ?? $brief;
            }

            $existing = collect();
        }

        $created = [];

        foreach ($chosen as $platform) {
            // Only ever a draft of the intent in hand. A published campaign on
            // this platform is what made $isTheThingInHand false above, which
            // cleared $existing, so the update branch below cannot reach one.
            //
            // It could, once, and a buyer asking to start a new campaign got the
            // published one edited instead: Mohsin typed "create campaing" on
            // 28 Sep and campaign 120250886412960429, already on Meta, was
            // renamed and then renamed back. Nothing reached Meta, so our name
            // and Meta's silently disagreed for the length of one turn, and a
            // push of pending changes in between would have made it permanent.
            //
            // That was answered with a refusal, because a second campaign on one
            // platform in one conversation had nowhere to live. It has one now -
            // its own brief - so the answer is to make it rather than refuse it.
            $campaign = $existing->firstWhere('platform', $platform);

            if ($campaign) {
                $platformObjective = $this->objectiveForPlatform($objective, $platform);

                if (filled($platformObjective) && $campaign->objective !== $platformObjective) {
                    $campaign->update(['objective' => $platformObjective]);
                    $this->workspace->recordSource($campaign, 'objective', ArtifactFieldSource::MODEL_INFERRED);
                }

                if (filled($arguments['name'] ?? null) && $campaign->name !== (string) $arguments['name']) {
                    $campaign->update(['name' => (string) $arguments['name']]);
                    $this->workspace->recordSource($campaign, 'name', ArtifactFieldSource::USER_STATED);
                }
            } else {
                $campaign = Campaign::query()->create([
                    'user_id' => auth()->id(),
                    'brief_id' => $brief?->id,
                    // Generated when not given. Asking someone to name a campaign
                    // before it exists is a question about our data model, not about
                    // their advertising, and it can be renamed at any point.
                    'name' => $this->nameFor($arguments['name'] ?? null, $platform, $brief),
                    'platform' => $platform,
                    'objective' => $this->objectiveForPlatform($objective, $platform),
                    // Set here when the platform runs on one account, so it is
                    // never a question. Null for Meta, where it genuinely is one.
                    'ad_account_id' => $this->platforms->for($platform)->defaultAdAccountId(),
                    // Click tracking is not a decision anybody wants to make. Every
                    // campaign should carry it, the standard tagging is right almost
                    // always, and asking cost a question and an answer to arrive at
                    // the value that was going to be used anyway. Set from the
                    // platform's own macros; the buyer is told and can change it.
                    'utm' => $this->platforms->for($platform)->trackingOptions()[0]['value'] ?? null,
                    'status' => 'draft',
                ]);

                // The user named the campaign; the objective and the platform are the
                // model's reading unless they said so outright, so both are marked as
                // inferred and will need confirming before anything spends.
                $this->workspace->recordSource(
                    $campaign,
                    'name',
                    filled($arguments['name'] ?? null) ? ArtifactFieldSource::USER_STATED : ArtifactFieldSource::FALLBACK,
                );

                // Not USER_STATED. This used to claim the buyer picked the platform
                // whatever happened, and nothing here can tell a pick from a guess:
                // choosing from the chooser arrives as an ordinary message, exactly
                // like the model deciding on its own. Seen on dev on 23 Sep, in a
                // chat where Meta was never mentioned once: the campaign was created
                // on Meta and the provenance told the agent the user had asked for
                // it, so nothing ever questioned it. Recording it as the model's own
                // reading is the truthful half; the description below is what stops
                // the guess being made in the first place.
                $this->workspace->recordSource($campaign, 'platform', ArtifactFieldSource::MODEL_INFERRED);

                if (filled($campaign->ad_account_id)) {
                    $this->workspace->recordSource($campaign, 'ad_account_id', ArtifactFieldSource::PLATFORM_RETURNED);
                }

                if (filled($campaign->utm)) {
                    $this->workspace->recordSource($campaign, 'utm', ArtifactFieldSource::PLATFORM_RETURNED);
                }

                if (filled($this->objectiveForPlatform($objective, $platform))) {
                    $this->workspace->recordSource($campaign, 'objective', ArtifactFieldSource::MODEL_INFERRED);
                }

                // No brief to join yet means one thing now: the conversation
                // does not exist, which is the first message of a new chat.
                // Remembered so Briefs::settle() can attach it once it does.
                //
                // There used to be a second reason - a brief deliberately
                // withheld from a later, unrelated campaign - and the two were
                // indistinguishable here, so the withheld one was remembered
                // and adopted anyway. That reason is gone: a second intent is
                // given its own brief above rather than none, so null means
                // only the first-message case.
                if ($brief === null) {
                    $this->briefs->orphaned($campaign);
                }
            }

            // The first is what the user is talking about; produced() focuses
            // whatever it is given, so the later ones are linked without
            // stealing focus from it.
            $this->workspace->produced($campaign, $request->toolCallId(), focus: $created === []);
            $created[] = $campaign;
        }

        $first = $created[0];

        return $this->json(array_filter([
            'ok' => true,
            // Said so the model does not describe a brand new campaign as a
            // change to the published one the buyer can still see on screen.
            'note_on_existing' => $clash->contains(fn (Campaign $c): bool => $c->isPublished())
                ? 'A published campaign already exists on this platform. It was left exactly as it is, '
                    .'and this is a separate new campaign with its own budget and its own settings. '
                    .'Say so, and do not describe it as an edit to the published one.'
                : null,
            'campaign_id' => $first->id,
            'name' => $first->name,
            'platform' => $first->platform,
            'status' => $first->status,
            'now_in_focus' => true,
            'campaigns' => array_map(fn (Campaign $c): array => [
                'campaign_id' => $c->id,
                'platform' => $c->platform,
                'name' => $c->name,
            ], $created),
            // Said back so the model tells the user the shared questions are
            // coming once rather than once per platform.
            'note' => count($created) > 1
                ? 'These share one brief, so the landing page, budget, dates and creative are asked once for all of them.'
                : null,
        ], fn (mixed $value): bool => $value !== null));
    }

    /**
     * The platforms asked for, however they were given.
     *
     * A list when several were picked, a single string when the model used the
     * older argument, and empty when nothing was chosen yet.
     *
     * @param  array<string, mixed>  $arguments
     * @return list<string>
     */
    private function platformsFrom(array $arguments): array
    {
        $given = $arguments['platforms'] ?? $arguments['platform'] ?? [];

        return collect(is_array($given) ? $given : [$given])
            ->map(fn (mixed $platform): string => strtolower(trim((string) $platform)))
            ->filter()
            // Picking the same platform twice is one campaign, not two.
            ->unique()
            ->values()
            ->all();
    }

    private function offerPlatforms(): void
    {
        // Asked of the platform rather than matched on its name here. This was
        // a copy of the same knowledge the prompt needed, and the two disagreed:
        // LinkedIn counted as available because the MCP flag defaulted on, so a
        // buyer with no LinkedIn credentials was shown it badged "Connected".
        $isAvailable = fn (string $key): bool => $this->platforms->for($key)->isConfigured();

        $keys = array_keys((array) config('platforms.rules'));

        // Prioritize Meta, Google Ads, LinkedIn on the top line, followed by other platforms
        $topPriority = ['meta', 'google', 'linkedin'];
        usort($keys, function (string $a, string $b) use ($topPriority, $isAvailable): int {
            $aIndex = array_search($a, $topPriority, true);
            $bIndex = array_search($b, $topPriority, true);
            $aPriority = $aIndex !== false ? $aIndex : 999;
            $bPriority = $bIndex !== false ? $bIndex : 999;

            if ($aPriority !== $bPriority) {
                return $aPriority <=> $bPriority;
            }

            return ($isAvailable($b) ? 1 : 0) <=> ($isAvailable($a) ? 1 : 0);
        });

        $this->choices->offer(
            field: 'platforms',
            question: 'Where should this run?',
            options: array_map(fn (string $key): array => [
                'value' => $key,
                'label' => $this->platforms->for($key)->name(),
                'hint' => $isAvailable($key) ? 'Ready to publish' : 'Draft only, not connected yet',
                'badge' => $isAvailable($key) ? 'Connected' : null,
                'sends' => 'Advertise on '.$this->platforms->for($key)->name(),
            ], $keys),
            // More than one, because the whole point of the brief is that the
            // same thing can run in several places without being set up twice.
            multiple: true,
            allowOther: false,
        );
    }

    private function json(array $payload): string
    {
        return json_encode($payload, JSON_UNESCAPED_SLASHES);
    }
}
