<?php

namespace App\Campaigns;

use App\Agent\Workspace;
use App\Campaigns\Targeting\LinkedInAudienceSize;
use App\Campaigns\Targeting\MetaDetailedTargeting;
use App\Campaigns\Targeting\SearchKeywordSelections;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Asset;
use App\Models\Brief;
use App\Models\Campaign;

/**
 * The order a campaign gets built in, and what is left.
 *
 * Options made each answer a click, but the agent still waited to be asked what
 * came next, so the user had to drive. This is the missing half: a fixed order,
 * derived from what the campaign already holds rather than from anything the
 * model remembers, so "next" is the same answer every turn.
 *
 * Order follows the launch flow on SERP-1833: account and assets, then the
 * campaign, then the ad set, then creative, then verification. Within that,
 * things that unlock other things come first: a Page and pixel cannot be listed
 * until an ad account is chosen, and the objective decides whether a pixel is
 * needed at all.
 */
class LaunchFlow
{
    /**
     * The shared questions asked before any platform is chosen.
     *
     * These belong to the brief, not to a campaign: the page being advertised,
     * the money and the dates are the same answer however many platforms it
     * runs on. Asking them once is the whole point of the brief, and asking
     * them first means everything after can be a recommendation drawn from the
     * page rather than a blank question.
     *
     * @var list<array{key: string, label: string, tool: string, offers: bool, ask?: string}>
     */
    private const BRIEF_SETUP = [
        ['key' => 'landing_url', 'label' => 'landing page', 'tool' => 'analyze_landing_page', 'offers' => false,
            'ask' => 'What are you promoting? Paste the URL of the page the ads should send people to.'],
    ];

    /** Shared financial questions run after targeting and use the selected account currency. */
    private const BRIEF_BUDGET = [
        ['key' => 'budget', 'label' => 'budget', 'tool' => 'set_campaign_budget', 'offers' => true,
            'ask' => 'How should the budget work, and how much?'],
        ['key' => 'schedule', 'label' => 'end date', 'tool' => 'set_schedule', 'offers' => true,
            'ask' => 'When should it stop?'],
    ];

    /**
     * The shared questions asked last, once every platform is configured.
     *
     * Creative and copy are reused across platforms, so they are the brief's
     * too. They come last because writing the copy is what pairs each ad with a
     * creative, and there is nothing to pair until the campaign exists.
     *
     * @var list<array{key: string, label: string, tool: string, offers: bool, ask?: string}>
     */
    private const BRIEF_CREATIVE = [
        ['key' => 'creatives', 'label' => 'creatives', 'tool' => 'import_creatives', 'offers' => true,
            'ask' => 'Which creatives should be used?'],
        ['key' => 'copy_emphasis', 'label' => 'ad highlight', 'tool' => 'write_ad_copy', 'offers' => true,
            'arguments' => ['offer_emphasis' => true], 'ask' => 'What should these ads highlight?'],
        ['key' => 'copy', 'label' => 'ad copy', 'tool' => 'write_ad_copy', 'offers' => false,
            'ask' => 'Writing the ad copy now.'],
        ['key' => 'copy_selection', 'label' => 'ad variation', 'tool' => 'choose_ad_copy', 'offers' => true,
            'arguments' => ['offer_selection' => true], 'ask' => 'Which variation should we use?'],
        ['key' => 'cta', 'label' => 'call to action', 'tool' => 'choose_call_to_action', 'offers' => true,
            'ask' => 'Which button should the ad carry?'],
    ];

    /**
     * Every step for this campaign, shared and platform, in the order asked.
     *
     * The platform's own steps sit in the middle: after the brief has settled
     * what is being advertised and for how much, and before the creative that
     * every platform shares. A second platform therefore only ever repeats the
     * middle, which is five or six questions rather than fifteen.
     *
     * @return list<array{key: string, label: string, tool: string, offers: bool, ask?: string}>
     */
    public function steps(Campaign $campaign): array
    {
        $platformRules = $this->platforms->for($campaign);
        $platformSteps = $platformRules->steps();
        $step = static fn (string $key): ?array => collect($platformSteps)->firstWhere('key', $key);
        $platformSetup = collect(['campaign_type', 'objective', 'special_ad_categories', 'ad_account'])
            ->map($step)
            ->filter()
            ->values()
            ->all();
        $page = $step('page');
        $instagram = $step('instagram');
        $identity = collect(['pixel', 'conversion_event'])
            ->map($step)
            ->filter()
            ->values()
            ->all();
        $placements = $platformRules->placements() === [] ? [] : [[
            'key' => 'placements', 'label' => 'placements', 'tool' => 'set_targeting', 'offers' => true,
            'arguments' => ['section' => 'placements'], 'ask' => 'Where should these ads appear?',
        ]];
        $metaPlacements = $campaign->platform === 'meta' ? $placements : [];
        $devices = in_array($campaign->platform, ['meta', 'google'], true) ? [[
            'key' => 'devices', 'label' => 'devices', 'tool' => 'set_targeting', 'offers' => true,
            'arguments' => ['section' => 'devices'], 'ask' => 'Which devices should these ads reach?',
        ]] : [];
        $locationScope = $step('location_scope');
        $bidding = $step('bidding');
        $handledPlatformSteps = [
            'campaign_type', 'objective', 'special_ad_categories', 'ad_account', 'page', 'instagram',
            'pixel', 'conversion_event', 'bidding', 'targeting', 'location_scope',
        ];
        $additionalPlatformSteps = collect($platformSteps)
            ->reject(fn (array $platformStep): bool => in_array($platformStep['key'], $handledPlatformSteps, true))
            ->values()
            ->all();
        $copySelectionAdSetId = $this->copySelectionAdSetId($campaign);
        $copySelection = [
            'key' => 'copy_selection', 'label' => 'ad variation', 'tool' => 'choose_ad_copy', 'offers' => true,
            'arguments' => array_filter([
                'offer_selection' => true,
                'ad_set_id' => $copySelectionAdSetId,
            ], fn (mixed $value): bool => $value !== null),
            'ask' => 'Which variation should we use?',
        ];
        $targeting = $step('targeting') !== null;
        $targetSteps = $targeting ? [
            ...($campaign->platform === 'meta' ? [] : $placements),
            ...$devices,
            ['key' => 'countries', 'label' => 'countries', 'tool' => 'set_targeting', 'offers' => true,
                'arguments' => ['section' => 'countries'], 'ask' => 'Which countries should these ads target?'],
            ...($locationScope === null ? [] : [$locationScope]),
        ] : [];

        return [
            ...self::BRIEF_SETUP,
            ...$platformSetup,
            ...$metaPlacements,
            ...($page === null ? [] : [$page]),
            ...($instagram === null ? [] : [$instagram]),
            ...$identity,
            ...$targetSteps,
            ...$additionalPlatformSteps,
            ...self::BRIEF_BUDGET,
            ...($bidding === null ? [] : [$bidding]),
            ...array_map(fn (array $step): array => $step['key'] === 'copy_selection' ? $copySelection : $step, self::BRIEF_CREATIVE),
            ...($campaign->platform === 'meta' ? [[
                'key' => 'verified_advertiser',
                'label' => 'verified advertiser',
                'tool' => 'choose_verified_advertiser',
                'offers' => true,
                'ask' => 'Which verified advertiser should these ads use?',
            ]] : []),
        ];
    }

    private function copySelectionAdSetId(Campaign $campaign): ?int
    {
        $primaryAdSetId = $campaign->primaryAdSet?->getKey();
        $variationSet = $campaign->ads()
            ->whereNull('external_ad_id')
            ->get(['ad_set_id'])
            ->groupBy(fn ($ad): string => (string) ($ad->ad_set_id ?? $primaryAdSetId ?? 0));
        $sources = $this->workspace->sourcesFor($campaign);

        foreach ($variationSet as $groupId => $ads) {
            if ($ads->count() <= 1 || array_key_exists('copy_selection_adset_'.$groupId, $sources)) {
                continue;
            }

            $adSetId = $ads->first()->ad_set_id ?? $primaryAdSetId;

            if ($adSetId !== null) {
                return (int) $adSetId;
            }
        }

        return null;
    }

    public function __construct(
        private readonly Platforms\Platforms $platforms,
        private readonly Workspace $workspace,
        private readonly TargetingSelections $targetingSelections,
        private readonly SearchKeywordSelections $searchKeywords,
    ) {}

    /**
     * The question to ask before a campaign exists at all.
     *
     * The rest of the flow reads a campaign, so until one exists there is no
     * flow and the model was left to open the conversation however it liked.
     * What it did was ask which platform to advertise on, which is the one
     * question the buyer has least reason to care about first.
     *
     * So the opening question is the landing page, answerable before anything
     * has been created, and the thing every later suggestion is drawn from.
     * Only that one: the rest of the brief is worth asking once there is a
     * platform to size it against.
     *
     * @return array{key: string, label: string, tool: string, offers: bool, ask?: string}|null
     */
    public function beforeCampaign(?Brief $brief): ?array
    {
        if ($brief !== null && filled($brief->landing_url)) {
            return null;
        }

        return collect(self::BRIEF_SETUP)->firstWhere('key', 'landing_url');
    }

    /**
     * The next thing that needs answering, or null when the campaign is whole.
     *
     * Publishing ends the flow. These steps describe building a campaign up to
     * the moment it first reaches the platform, and after that they are not
     * questions any more: the campaign is live, the answers are on Meta, and the
     * things worth doing next are of a different kind - pushing an edit, adding
     * an ad set, adding ads, starting or pausing it.
     *
     * Nothing said so, and it was the strongest steer in the product. The
     * instructions turn this into "NEXT STEP ... do not raise anything later in
     * the list unprompted", so on a published campaign still missing a creative
     * the model kept asking for creatives whatever it was asked for. Found on
     * the dev server on 5 Oct: "add another ad set to this live campaign" four
     * times, twice naming add_ad_set outright, answered each time by the flow's
     * next step instead. add_ad_set and add_ads were unreachable because of it.
     *
     * outstandingElsewhere() has always skipped published siblings for exactly
     * this reason - "a campaign already on the platform is not waiting for
     * anything" - and that is as true of the campaign in focus.
     *
     * @return array{key: string, label: string, tool: string, offers: bool, ask?: string}|null
     */
    public function next(Campaign $campaign): ?array
    {
        if ($campaign->isPublished()) {
            return $this->advertiserStillRequired($campaign);
        }

        foreach ($this->steps($campaign) as $step) {
            if (! $this->done($campaign, $step['key'])) {
                return $step;
            }
        }

        return null;
    }

    /**
     * A campaign already on the account is not walked again, except this.
     *
     * The ad set is where Meta asks for a verified advertiser, and that ask
     * arrives after the campaign itself has been created. The failure leaves
     * the campaign on the account, which would otherwise end the questions
     * before the buyer can choose the advertiser the retry needs.
     *
     * @return array{key: string, label: string, tool: string, offers: bool, ask?: string}|null
     */
    private function advertiserStillRequired(Campaign $campaign): ?array
    {
        $required = ($campaign->meta['verified_advertiser_required'] ?? false) === true
            || str_contains((string) $campaign->last_error, '3858634');

        if (! $required || $this->done($campaign, 'verified_advertiser')) {
            return null;
        }

        $step = collect($this->steps($campaign))->firstWhere('key', 'verified_advertiser');

        return is_array($step) ? $step : null;
    }

    /**
     * What is still outstanding on the other campaigns of the same brief.
     *
     * Everything else here reports on the campaign in focus, which is right for
     * asking the next question and wrong for saying whether the work is done.
     * A conversation advertising on two platforms holds two campaigns, and the
     * buyer is looking at one of them.
     *
     * Seen on dev on 23 Sep: a Meta and Google thread where every "write the ad
     * copy" landed on Google, because Google was in focus. Meta finished with no
     * ads at all and the chat said "Everything is ready. Shall I publish this
     * campaign?" - true of what was on screen, and not of the campaign sitting
     * behind it.
     *
     * Keyed by campaign name, because that is what the buyer sees on the tabs.
     *
     * @return array<string, string> campaign name to the step it is waiting on
     */
    public function outstandingElsewhere(Campaign $focus): array
    {
        $brief = $focus->brief;

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

        $waiting = [];

        foreach ($brief->campaigns()->where('id', '!=', $focus->id)->get() as $sibling) {
            // A campaign already on the platform is not waiting for anything.
            if ($sibling->isPublished()) {
                continue;
            }

            if ($step = $this->next($sibling)) {
                $waiting[$sibling->name] = $step['label'];
            }
        }

        return $waiting;
    }

    /**
     * Every step, with whether it is settled, for showing progress.
     *
     * @return list<array{key: string, label: string, done: bool}>
     */
    public function progress(Campaign $campaign): array
    {
        $pendingSchedule = $this->pendingSchedule($campaign);

        return array_map(fn (array $step): array => [
            'key' => $step['key'],
            'label' => $step['label'],
            'done' => $this->done($campaign, $step['key'], $pendingSchedule),
        ], array_values(array_filter(
            $this->steps($campaign),
            fn (array $step): bool => $this->applies($campaign, $step['key'], $pendingSchedule),
        )));
    }

    /**
     * Whether a step applies at all.
     *
     * A traffic campaign needs no pixel, so asking for one is not a step that
     * is outstanding, it is a step that does not exist. A date is the same: a
     * campaign that runs until someone stops it needs no end date, and only a
     * lifetime budget makes one compulsory, because it is the total to spend by
     * then.
     */
    private function pendingSchedule(Campaign $campaign): bool
    {
        return collect($this->workspace->pendingChoices())->contains(fn (array $choice): bool => ($choice['field'] ?? null) === 'ends_at'
            && (string) ($choice['focus_id'] ?? '') === (string) $campaign->getKey());
    }

    private function applies(Campaign $campaign, string $key, ?bool $pendingSchedule = null): bool
    {
        return match ($key) {
            // Asked of the platform, not of a list of platform names kept here.
            //
            // This read $campaign->platform === 'meta', which happens to be the
            // same answer today, and PublishGate already asks requiresPage().
            // The two agreeing by coincidence is the problem: the moment a
            // platform is told it needs a Page, the gate blocks on a missing
            // one while the flow never asks for it, and the campaign cannot
            // publish and cannot be fixed. LinkedIn is a live candidate for
            // exactly that, since every sponsored post needs an organization.
            'page' => $this->platforms->for($campaign)->requiresPage(),
            'special_ad_categories' => $this->platforms->for($campaign)->specialAdCategories() !== [],
            'pixel' => filled($campaign->objective)
                && $this->platforms->for($campaign)->requiresPixel($campaign->objective),
            // Only where a pixel event is what the ad set optimises toward, and
            // only once the pixel it reads the events from has been chosen. A
            // traffic campaign promotes the Page and Meta rejects an event sent
            // against it.
            'conversion_event' => filled($campaign->objective)
                && filled($campaign->pixel_id)
                && $this->platforms->for($campaign)->conversionEvent($campaign->objective) !== null,
            'schedule' => $campaign->usesLifetimeBudget()
                || ($pendingSchedule ?? $this->pendingSchedule($campaign)),
            'linkedin_lead_form' => $campaign->platform === 'linkedin' && $campaign->objective === 'LEAD_GENERATION',
            'linkedin_conversion' => $campaign->platform === 'linkedin' && $campaign->objective === 'WEBSITE_CONVERSIONS',
            'linkedin_insight_tag' => $campaign->platform === 'linkedin' && $campaign->objective === 'WEBSITE_CONVERSIONS',
            'linkedin_audience' => $campaign->platform === 'linkedin',
            // Only an Instagram placement makes an Instagram account relevant.
            'instagram' => in_array('instagram', (array) ($campaign->placements ?? []), true),
            // Only where the platform sells more than one kind of campaign.
            'campaign_type' => $this->platforms->for($campaign)->campaignTypes() !== [],
            // The contract PlatformRules already states for defaultAdAccountId:
            // "a platform answering this has no ad account step: the id is set
            // when the campaign is created". That was documented and then not
            // read anywhere, so every platform got the step and the ones that
            // fill the id in showed it permanently ticked.
            //
            // Asked of the platform rather than by name, like requiresPage()
            // above. Google is the reason it matters now: a Google login is a
            // manager with child accounts under it, and only the allow list says
            // which of them this instance may buy on. One permitted account is
            // not a choice, so GoogleRules fills it in and no step is asked;
            // two or more, or a wildcard, and it answers null so the buyer
            // picks. LinkedIn answers with its shared account id wherever one is
            // configured, so there it also loses a step it could only ever have
            // shown as already done; with none configured it answers null and
            // keeps the step, which is the same before and after this.
            'ad_account' => $this->platforms->for($campaign)->defaultAdAccountId() === null,
            'countries' => $campaign->platform !== 'unsupported',
            'placements' => $this->platforms->for($campaign)->placements() !== [],
            'devices' => in_array($campaign->platform, ['meta', 'google'], true),
            // Display and Performance Max have no keyword list; only Search does.
            'search_keywords' => $campaign->platform === 'google'
                && ($campaign->campaign_type ?: 'search') === 'search',
            'audience' => $campaign->platform === 'meta'
                && (array) ($campaign->special_ad_categories ?? []) === ['NONE'],
            'copy_emphasis' => ! $campaign->ads()->exists(),
            'copy_selection' => $campaign->platform !== 'google' && $this->copySelectionAdSetId($campaign) !== null,
            'cta' => $this->platforms->for($campaign)->callsToAction() !== [],
            'verified_advertiser' => $campaign->platform === 'meta',
            // A platform whose ads are text has nothing to attach a creative to.
            // Asking a Google Search campaign for an image is a step it can
            // never finish, and it sits in front of the ad copy that would.
            'creatives' => $this->platforms->for($campaign)->requiresCreativeAsset($campaign),
            'location_scope' => in_array($campaign->platform, ['meta', 'google', 'linkedin'], true)
                && ! $campaign->isPublished()
                && filled($this->targetingSelections->countries($campaign))
                && ($campaign->platform !== 'linkedin'
                    || in_array('US', $this->targetingSelections->countries($campaign), true)),
            default => true,
        };
    }

    private function metaAudienceReady(Campaign $campaign): bool
    {
        $mode = $campaign->audience['meta_audience_mode'] ?? null;
        $interests = is_array($campaign->audience['meta_interests'] ?? null) && $campaign->audience['meta_interests'] !== [];
        $narrowed = app(MetaDetailedTargeting::class)->hasNarrowing($campaign);

        if ($mode === 'broad' || ! empty($campaign->targetingSet()->first()?->options['meta_audiences'])) {
            return true;
        }

        if ($narrowed) {
            return ($campaign->meta['meta_audience_reviewed'] ?? false) === true;
        }

        return $mode === 'custom' && $interests;
    }

    private function done(Campaign $campaign, string $key, ?bool $pendingSchedule = null): bool
    {
        if (! $this->applies($campaign, $key, $pendingSchedule)) {
            return true;
        }

        return match ($key) {
            'ad_account' => filled($campaign->ad_account_id),
            'campaign_type' => filled($campaign->campaign_type),
            'objective' => filled($campaign->objective),
            // Null means nobody has answered. An empty list would be an answer,
            // which is why the column is nullable.
            'special_ad_categories' => $campaign->special_ad_categories !== null,
            'landing_url' => filled($campaign->landing_url),
            // An empty string is the answer "no tracking". Null is nobody
            // having been asked, which is how every ad so far went out untagged.
            'utm' => $campaign->utm !== null,
            'page' => filled($campaign->page_id),
            'linkedin_lead_form' => filled($campaign->meta['linkedin_setup']['lead_form']['id'] ?? null),
            'linkedin_conversion' => filled($campaign->meta['linkedin_setup']['conversion']['id'] ?? null),
            'linkedin_insight_tag' => filled($campaign->meta['linkedin_setup']['insight_tag']['id'] ?? null),
            'linkedin_audience' => (($campaign->meta['linkedin_audience_reviewed'] ?? false) === true
                || filled($campaign->targetingSet?->options['linkedin_segments'] ?? []))
                && ! app(LinkedInAudienceSize::class)->needsConfirmation($campaign),
            'pixel' => filled($campaign->pixel_id),
            'conversion_event' => filled($campaign->conversion_event),
            'budget' => $campaign->budget > 0,
            'bidding' => filled($campaign->bid_strategy)
                && (! $this->platforms->for($campaign)->bidStrategyNeedsTarget($campaign->bid_strategy)
                    || filled($campaign->bid_amount)),
            // A campaign that runs until it is paused has no end date, so the
            // date alone cannot say whether this was asked. Provenance can: the
            // tool records a source even when the answer was "none". Without
            // this, choosing no end date left the step outstanding and the
            // controller re-offered the dates on every later turn.
            'schedule' => $campaign->ends_at !== null
                || array_key_exists('ends_at', $this->workspace->sourcesFor($campaign)),
            // Countries always count. Placements only count where the platform
            // models them: Google declares none, so requiring one would leave
            // this step outstanding forever and the flow would never move past
            // targeting. See SetTargeting::supportedPlacements().
            'targeting' => filled($campaign->locations['countries'] ?? null)
                && (filled($campaign->placements)
                    || $this->platforms->for($campaign)->placements() === []),
            'countries' => $this->targetingSelections->countries($campaign) !== [],
            'placements' => filled($campaign->placements)
                || $this->platforms->for($campaign)->placements() === [],
            'devices' => filled($campaign->audience['devices'] ?? null),
            // An explicit selection, not criteria(), which also answers with
            // keywords derived from the landing page. Those are enough for the
            // publish gate but they are not an answer to the question: the step
            // would complete itself and the buyer would never see the terms
            // their money is being spent on.
            'search_keywords' => $this->searchKeywords->hasExplicitSelection($campaign),
            'audience' => $this->metaAudienceReady($campaign),
            'location_scope' => $this->targetingSelections->hasCompletedGeographyScope($campaign),
            // Empty string is "asked, and there is none", which the tool writes
            // when the account has no Instagram presence. Without that this step
            // could never be finished by an advertiser who simply has no handle.
            'instagram' => $campaign->instagram_account_id !== null,
            // What this step asks for is a creative to advertise with, which
            // lands in the conversation rather than on the campaign. Reading it
            // off the ads instead meant it could never be settled: no ad row
            // exists until the copy is written, one step later, so the flow
            // asked for creatives forever and never reached the copy that would
            // have finished it.
            //
            // An adopted campaign arrives in a conversation holding nothing, so
            // ads that already carry their creatives count too.
            'creatives' => $this->workspace->artifacts(Asset::class)->isNotEmpty()
                || ($campaign->ads()->exists() && ! $campaign->ads()->whereNull('asset_id')->exists()),
            'copy' => $campaign->ads()->exists(),
            'copy_emphasis' => array_key_exists('copy_emphasis', $this->workspace->sourcesFor($campaign)),
            'copy_selection' => $this->copySelectionAdSetId($campaign) === null,
            'cta' => array_key_exists('cta', $this->workspace->sourcesFor($campaign)),
            'verified_advertiser' => filled($campaign->meta['universal_beneficiary'] ?? null)
                || ($campaign->meta['verified_advertiser_status'] ?? null) === 'not_required',
            default => filled($campaign->{$key})
                || array_key_exists($key, $this->workspace->sourcesFor($campaign)),
        };
    }
}
