<?php

namespace App\Campaigns\Publishing;

use App\Campaigns\Creatives\DisplayImageShapes;
use App\Campaigns\Platforms\GoogleRules;
use App\Campaigns\Targeting\CountryCatalog;
use App\Campaigns\Targeting\GoogleAdAssets;
use App\Campaigns\Targeting\GoogleUserListSelections;
use App\Campaigns\Targeting\SearchKeywordSelections;
use App\Campaigns\Targeting\TargetingSelections;
use App\Campaigns\TrackedUrl;
use App\Models\Asset;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use RuntimeException;
use Throwable;

/**
 * Google's half of publishing: a paused campaign of the type the buyer chose.
 *
 * The work here is translation. GoogleAdsService already knows how to build a
 * paused Search campaign, and it has done since the Google chat shipped; what
 * it was never given was a campaign of ours to build it from. It read a
 * GoogleAdsDraft, filled in by a second agent in a second chat, so the campaign
 * a buyer assembled here, with its brief and its budget split and its publish
 * gate, was not the thing that reached Google.
 *
 * Search, Display and Performance Max. Search needs only words, so it is built
 * from the copy and the landing page alone. The other two run image ads, and
 * what they additionally need is gathered in displayExtras(): a business name
 * read from the page, a long headline taken from the longest copy that fits,
 * and the campaign's creatives uploaded to Google at the two sizes it demands.
 *
 * Video runs as part of Performance Max, from the YouTube id the campaign
 * holds. Shopping is the one type still absent, refused by GoogleRules rather
 * than here, because it needs a Merchant Center feed this product has no
 * concept of.
 */
class GooglePublisher implements PlatformPublisher
{
    public function __construct(
        private readonly GoogleAdsService $google,
        private readonly CountryCatalog $countries,
        private readonly TargetingSelections $selections,
        private readonly SearchKeywordSelections $searchKeywords,
        private readonly GoogleUserListSelections $userLists,
    ) {}

    /**
     * @param  array<string,mixed>  $created
     * @return array<string,mixed>
     */
    public function create(Campaign $campaign, string $actor, array &$created): array
    {
        if (array_key_exists('google_ad_group_criteria', (array) $campaign->external_ids)) {
            throw new RuntimeException('Imported Google Search criteria must be reviewed and rebuilt at their original ad-group scope before republishing.');
        }

        $connection = $this->connection($campaign);

        // $created is passed by reference and filled in as each object is made.
        // One call from here is several against Google, and a failure at the ad
        // group leaves a campaign and a budget already created. Reading the
        // return value alone would mean those ids only ever existed on success,
        // so every partial failure orphaned both on the account.
        $ids = $this->google->createPausedCampaign($connection, $this->payload($campaign), $created);

        foreach ($ids as $key => $value) {
            $created[$key] = $value;
        }

        // Follow the name Google actually gave it.
        //
        // createPausedCampaign settles a DUPLICATE_CAMPAIGN_NAME by taking the
        // next free variation, so the two can differ. Left alone, the draft and
        // the live campaign would disagree about their own name for ever: the
        // panel would show one, Google Ads the other, and every later diff
        // would read the difference as an edit the buyer had asked for and try
        // to push it back.
        if (filled($created['name'] ?? null) && (string) $created['name'] !== (string) $campaign->name) {
            $campaign->update(['name' => (string) $created['name']]);
        }

        return $created;
    }

    /**
     * Remove the campaign and the budget behind it.
     *
     * Only these two. Ad groups, keywords and ads live under the campaign and
     * go with it, which is the opposite of Meta, where a parent cannot be
     * deleted until its children are. The budget does not: it is an account
     * level object the campaign merely points at, so removing the campaign
     * alone leaves an orphan budget behind on every failed publish.
     *
     * @param  array<string,mixed>  $created
     * @return list<string> ids left behind; see {@see PlatformPublisher::rollBack()}
     */
    public function rollBack(Campaign $campaign, array $created, string $actor): array
    {
        $connection = GoogleAdsConnection::shared();

        // No connection means no call was ever made with it, so nothing of ours
        // is on the account to leave behind.
        if ($connection === null) {
            return [];
        }

        $customerId = str_replace('-', '', (string) $connection->customer_id);
        $left = [];

        // The campaign first and its budget second, because Google refuses to
        // remove a budget a campaign still references.
        $removals = [
            'campaigns' => $created['campaign_id'] ?? null,
            'campaignBudgets' => $created['budget_id'] ?? null,
        ];

        foreach ($removals as $collection => $id) {
            if (blank($id)) {
                continue;
            }

            try {
                $this->google->removeResource(
                    $connection,
                    'customers/'.$customerId.'/'.$collection.'/'.$id,
                    $collection,
                );
            } catch (Throwable $e) {
                // Named rather than logged, because this return value is what
                // Publisher records on the decision so the buyer can be told
                // what is still on their account.
                //
                // This used to return [] however the removals went:
                // removeResource caught everything and reported it, while the
                // comment here asserted it threw. Every Google rollback
                // therefore claimed a clean account, which is the failure
                // DeleteEntity's notes describe as leaving five live campaigns
                // with no record of them here.
                Log::warning('Google rollback could not remove a resource', [
                    'campaign' => $campaign->id,
                    'resource' => $collection.'/'.$id,
                    'error' => $e->getMessage(),
                ]);

                $left[] = $collection.'/'.$id;
            }
        }

        return $left;
    }

    /**
     * Google's tracking template for this campaign, or an empty string.
     *
     * The campaign's own value wins over the configured default, so one
     * campaign can be tagged differently without changing the install.
     */
    private function trackingTemplate(Campaign $campaign): string
    {
        $template = trim((string) ($campaign->meta['google_tracking_url_template']
            ?? config('google-ads.tracking_url_template', '')));

        // A template that does not carry the landing page through would send
        // every click to the same URL, so it is refused rather than sent.
        if ($template !== '' && ! str_contains($template, '{lpurl}')) {
            throw new RuntimeException('A Google tracking template has to contain {lpurl}, or every click goes to the same page.');
        }

        return $template;
    }

    /**
     * The one account this product buys on.
     *
     * Not the campaign owner's. Google Ads is one common internal access like
     * Meta, so who is typing does not decide which account is reached; it used
     * to, and a user without their own OAuth row could not publish at all.
     */
    private function connection(Campaign $campaign): GoogleAdsConnection
    {
        $connection = GoogleAdsConnection::shared()
            ?? throw new RuntimeException(GoogleAdsConnection::missingReason());

        $campaignCustomerId = preg_replace('/\D/', '', (string) $campaign->ad_account_id);

        if ($campaignCustomerId === '') {
            throw new RuntimeException('This campaign has no Google Ads account recorded. Choose one and review targeting again.');
        }

        // The account on the campaign wins, rather than being compared against
        // the configured one and refused. Once the chat asks which child of the
        // manager to use, the answer is the account: refusing it here meant a
        // buyer could answer every question and then be told at the publish
        // step that their own answer was wrong, with no step to go back to.
        //
        // This does not widen what may be reached. The id travels with every
        // call into CallLogger, which checks it against the allow list before
        // anything is sent, so an account nobody permitted is still refused -
        // just by the guard that exists for it, naming the right reason.
        return $connection->onCustomer($campaignCustomerId);
    }

    /**
     * Our campaign, in the shape GoogleAdsService builds from.
     *
     * @return array<string,mixed>
     */
    private function payload(Campaign $campaign): array
    {
        $ads = $campaign->ads()->orderBy('id')->get();
        $keywordCriteria = ($campaign->campaign_type ?? 'search') === 'search'
            ? $this->searchKeywords->criteria($campaign) : [];
        $userLists = $this->userLists->selected($campaign);

        if ($userLists !== []) {
            $userLists = $this->userLists->verifiedForPublish($campaign);
        }

        return [
            // The type the buyer chose, not a constant. Hardcoding 'search'
            // here while the flow offered three types would have quietly built
            // a Search campaign for somebody who picked Display, which is the
            // worst kind of wrong: it succeeds.
            //
            // Search is the fallback only for a campaign that predates the
            // question, which is every Google campaign built before today.
            'campaign_type' => $campaign->campaign_type ?: 'search',
            'name' => $campaign->name,
            'ad_group_name' => $campaign->name.' - ad group',
            // Performance Max names its asset group rather than an ad group,
            // and nothing here ever set it: only the unregistered MCP tool did,
            // so createPausedCampaign died on an undefined array key before any
            // request was made. The account has no asset groups at all, which
            // is what that looks like from outside.
            'asset_group_name' => $campaign->name.' - asset group',
            'daily_budget' => (float) $campaign->budget,
            'bidding_strategy' => (string) $campaign->bid_strategy,
            // Only the target strategies read this, and the gate has already
            // refused to publish one without it.
            'bid_target' => $campaign->bid_amount !== null ? (float) $campaign->bid_amount : null,
            // The landing page plus whatever tracking was agreed, built the same
            // way Meta's is so a click is tagged identically on both.
            // The template and the appended UTM are alternatives, never both.
            //
            // Google's template defines the click URL; TrackedUrl appends the
            // same kind of parameters to the final URL. Sending both tags every
            // click twice, so the final URL is sent clean whenever a template
            // is in play. Nothing changes where no template is configured,
            // which is the default.
            'final_url' => $this->trackingTemplate($campaign) === ''
                ? TrackedUrl::for($campaign)
                : (string) $campaign->landing_url,
            'tracking_url_template' => $this->trackingTemplate($campaign),
            'locations' => $this->locations($campaign),
            'excluded_locations' => $this->selections->googleGeoTargets($campaign)['excluded_geo_targets'] ?? [],
            'proximity_targets' => $this->selections->googleGeoTargets($campaign)['proximity_targets'] ?? [],
            'positive_geo_target_type' => $this->selections->googlePresenceMode($campaign),
            // Collected by set_targeting since the flow existed and never sent.
            // The buyer picked "mobile only", the panel showed mobile only, and
            // the campaign went out reaching every device Google has.
            'devices' => array_values((array) ($campaign->audience['devices'] ?? [])),
            // Collected by the shared flow and, until now, thrown away on the
            // way to Google. The networks a buyer picked were replaced by a
            // hardcoded set, the dates were never sent so a campaign with an
            // end date ran until somebody noticed, and the conversion action
            // the gate refuses to publish without went nowhere at all.
            'networks' => (array) ($campaign->placements ?? []),
            'starts_at' => $campaign->starts_at?->toDateString(),
            'ends_at' => $campaign->ends_at?->toDateString(),
            'conversion_action' => $campaign->pixel_id,
            // Approved, not derived.
            //
            // These were built from the landing page and attached without the
            // buyer ever seeing them, on the reasoning that a sitelink is just
            // another page on the advertiser's own site under its own label.
            // What that produced on a live campaign: sitelinks reading "PRSO
            // Peraso Inc. +54.13%" and "Login to continue", callouts reading
            // "Terms of Use" and "Continue". Scraped ticker rows and auth links
            // as published ad copy, and the buyer's first sight of them was in
            // Google Ads asking where they came from.
            //
            // A blocklist cannot fix that, because the thing being filtered is
            // every link on every page anyone might advertise. So nothing is
            // sent unless it was approved: ad assets are copy, and copy is
            // chosen. GoogleAdAssets still proposes the candidates - see
            // ChooseAdCopy, which puts them on screen beside the headlines.
            ...$this->approvedAssets($campaign),
            // Every action the buyer chose. conversion_action stays as the
            // first so anything reading one value is unaffected.
            'conversion_actions' => array_values(array_unique(array_filter([
                (string) $campaign->pixel_id,
                ...(array) ($campaign->meta['google_conversion_actions'] ?? []),
            ]))),
            // Search only; the display and performance max create paths never
            // read this, and demanding it there threw before they could run.
            'keywords' => implode(', ', array_column(array_values(array_filter(
                $keywordCriteria, static fn (array $keyword): bool => ! $keyword['negative'],
            )), 'text')),
            'keyword_criteria' => $keywordCriteria,
            'user_lists' => $userLists,
            // Capped at what a responsive search ad holds. Six descriptions,
            // which three ads produce as a matter of course, is refused whole
            // with "TOO_MANY" and no mention of which field.
            //
            // Narrowed first to whatever the buyer ticked. Before that screen
            // existed this took the first four descriptions written and the
            // choice of which was nobody's.
            'headlines' => array_slice(
                $this->keptLines($campaign, 'headlines', $this->copy($ads, 'headline'), GoogleRules::MIN_HEADLINES),
                0,
                GoogleRules::MAX_HEADLINES,
            ),
            'descriptions' => array_slice(
                $this->keptLines(
                    $campaign,
                    'descriptions',
                    $this->copy($ads, 'description', 'primary_text'),
                    GoogleRules::MIN_DESCRIPTIONS,
                ),
                0,
                GoogleRules::MAX_DESCRIPTIONS,
            ),
            // Shown after the domain on a search ad, and not part of the real
            // URL. Held on the campaign rather than per row, because one
            // responsive search ad is built from every row and they describe
            // that one ad.
            ...(array) ($campaign->meta['google_display_paths'] ?? []),
            ...$this->displayExtras($campaign, $ads),
        ];
    }

    /**
     * What Display needs that Search does not, and Search ignores.
     *
     * Display runs image ads, so it needs pictures at two exact sizes and the
     * name of the business they are advertising, neither of which a Search
     * campaign has any use for. Returned as an empty array for Search rather
     * than branching the whole payload, because everything else is identical.
     *
     * The images are uploaded to Google here, at publish time, rather than when
     * the creative was made. An asset only needs to exist on Google if a
     * campaign actually uses it, and uploading on creation would put every
     * creative anyone generates onto the ad account.
     *
     * @param  Collection<int, CampaignAd>  $ads
     * @return array<string,mixed>
     */
    private function displayExtras(Campaign $campaign, $ads): array
    {
        if (($campaign->campaign_type ?: 'search') === 'search') {
            return [];
        }

        $connection = $this->connection($campaign);
        $sorted = $this->imagesByShape($campaign);
        $shapes = $sorted['shapes'];

        // Refused here, before the campaign and the budget exist.
        //
        // This is what the old exact-size match was trying to do and did the
        // opposite of: anything that was not precisely 1200x628 or 1200x1200
        // was dropped without a word, both slots came out empty, and Google
        // refused the ad afterwards with an error naming no field - having
        // already taken the campaign and the budget, which then had to be
        // rolled back. A buyer who attached a perfectly good 1920x1005 image
        // had no way to find out that was why.
        $missing = array_values(array_filter(
            ['landscape', 'square'],
            fn (string $shape): bool => $shapes[$shape] === [],
        ));

        if ($missing !== []) {
            $needed = array_map(DisplayImageShapes::describe(...), $missing);

            throw new RuntimeException(sprintf(
                'This campaign needs an image %s. %s Nothing was created.',
                implode(' and an image ', $needed),
                $sorted['rejected'] === []
                    ? 'No image creative is attached to it.'
                    : 'What is attached: '.implode('; ', $sorted['rejected']).'.',
            ));
        }

        return [
            'business_name' => $this->businessName($campaign),
            // Google allows 90 characters here against 30 for a headline, so
            // the body copy is the better source: a headline padded out to
            // length would just repeat itself.
            'long_headline' => $this->longHeadline($campaign, $ads),
            'long_headlines' => [$this->longHeadline($campaign, $ads)],
            'marketing_image_assets' => $this->uploadImages($connection, $shapes['landscape']),
            'square_marketing_image_assets' => $this->uploadImages($connection, $shapes['square']),
            // Performance Max is the only type with a portrait slot. A
            // responsive display ad has no field for one, so a 4:5 image is
            // genuinely unusable there rather than merely unused.
            'portrait_marketing_image_assets' => $campaign->campaign_type === 'performance_max'
                ? $this->uploadImages($connection, $shapes['portrait'])
                : [],
            // Performance Max only. Google will not run an asset group without
            // a logo and will not take a marketing image as one, so the buyer
            // names it in attach_creatives rather than it being guessed from
            // whatever square happens to be attached.
            'logo_image_assets' => $campaign->campaign_type === 'performance_max'
                ? $this->uploadLogo($campaign, $connection)
                : [],
            'youtube_video_assets' => $this->uploadVideo($campaign, $connection),
        ];
    }

    /**
     * The YouTube video, where one was named, as a Google asset.
     *
     * Optional: Performance Max runs without video, it simply reaches less
     * inventory, so a campaign without one is not blocked over it.
     *
     * Created here rather than stored, because a Google video asset belongs to
     * an account. We hold the YouTube id, which is the thing that is true
     * wherever the campaign runs, and turn it into an asset at publish time.
     *
     * Google Ads video assets must reference a YouTube video. There is no path
     * that uploads one of our rendered files, so this never pretends to: a
     * campaign with a local video and no YouTube id simply has no video asset.
     *
     * @return list<string>
     */
    private function uploadVideo(Campaign $campaign, GoogleAdsConnection $connection): array
    {
        if (blank($campaign->youtube_video_id)) {
            return [];
        }

        return [$this->google->createYouTubeVideoAsset(
            $connection,
            (string) $campaign->youtube_video_id,
            $campaign->name.' video',
        )];
    }

    /**
     * Who the ad says it is from.
     *
     * Taken from the landing page's title rather than asked for. The page is
     * the business, the title almost always names it, and the brief already
     * holds the analysis, so asking would be asking somebody to retype
     * something they already gave us.
     *
     * Capped at Google's 25 character limit, on a word boundary where one is
     * available, because Google refuses a longer one outright.
     */
    private function businessName(Campaign $campaign): string
    {
        $title = trim((string) ($campaign->brief?->pageAnalysis()?->title ?? $campaign->name));

        // Page titles are routinely "Brand | Tagline" or "Brand - Tagline", and
        // the part before the separator is the bit that names the business.
        $name = trim((string) preg_split('/\s+[|\-–—:]\s+/u', $title)[0]);

        if ($name === '') {
            $name = $campaign->name;
        }

        return mb_strlen($name) <= 25 ? $name : rtrim(mb_substr($name, 0, 25));
    }

    /**
     * The long headline Display shows when it has room for one.
     *
     * The longest piece of copy that fits, because this is the one field where
     * Google gives more space than Meta ever does and truncating into it would
     * waste it.
     *
     * @param  Collection<int, CampaignAd>  $ads
     */
    private function longHeadline(Campaign $campaign, $ads): string
    {
        $candidates = $ads
            ->flatMap(fn ($ad): array => [$ad->primary_text, $ad->description, $ad->headline])
            ->filter(fn (?string $text): bool => filled($text))
            ->map(fn (string $text): string => trim($text))
            ->filter(fn (string $text): bool => mb_strlen($text) <= 90)
            ->sortByDesc(fn (string $text): int => mb_strlen($text));

        return (string) ($candidates->first() ?? mb_substr((string) $campaign->name, 0, 90));
    }

    /**
     * The shapes Google takes, and the smallest it takes them at.
     *
     * Its own minimums, not its recommendations. 1200x628 and 1200x1200 are
     * what Google suggests; 600x314 and 300x300 are what it requires, and the
     * ratio is the part that actually has to be right.
     *
     * The tolerance is tight enough to keep 16:9 out of the landscape slot,
     * which is seven per cent away and the near miss most likely to be
     * uploaded by accident.
     */

    /**
     * Every image creative on the campaign, sorted into the shapes Google uses.
     *
     * Read once rather than once per shape. It used to be called per slot, so
     * each file was pulled off the disk and measured two or three times over.
     *
     * @return array{shapes: array<string, list<array{contents: string, name: string}>>, rejected: list<string>}
     */
    private function imagesByShape(Campaign $campaign): array
    {
        $shapes = array_fill_keys(array_keys(DisplayImageShapes::SHAPES), []);
        $rejected = [];

        foreach ($campaign->ads()->with('asset')->get() as $ad) {
            $asset = $ad->asset;

            if ($asset === null || $asset->kind !== 'image') {
                continue;
            }

            $disk = Storage::disk($asset->disk ?: 'local');

            if (! $disk->exists($asset->path)) {
                continue;
            }

            $contents = $disk->get($asset->path);
            $size = @getimagesizefromstring($contents);

            if (! is_array($size) || $size[0] < 1 || $size[1] < 1) {
                continue;
            }

            [$width, $height] = $size;
            $name = $asset->original_name ?: $campaign->name.' '.$width.'x'.$height;
            $matched = null;

            foreach (DisplayImageShapes::SHAPES as $shape => $spec) {
                if (DisplayImageShapes::shapeOf($width, $height) !== $shape) {
                    continue;
                }

                // Right shape, too small. Named rather than skipped silently,
                // because "your image is the wrong size" is something a buyer
                // can act on and an empty slot is not.
                if ($width < $spec['min_width'] || $height < $spec['min_height']) {
                    $rejected[] = sprintf(
                        '%s is %dx%d, which is %s but below Google\'s minimum of %dx%d',
                        $name, $width, $height, $spec['label'], $spec['min_width'], $spec['min_height'],
                    );

                    $matched = $shape;

                    break;
                }

                $shapes[$shape][] = ['contents' => $contents, 'name' => $name];
                $matched = $shape;

                break;
            }

            if ($matched === null) {
                $rejected[] = sprintf('%s is %dx%d, which is none of the shapes Google takes', $name, $width, $height);
            }
        }

        return ['shapes' => $shapes, 'rejected' => $rejected];
    }

    /**
     * The creative the buyer named as the brand logo.
     *
     * Refused rather than skipped when it is missing, for the reason the image
     * shapes above are: Google rejects an asset group with no logo, and doing
     * that after the campaign and budget exist turns a clear question into an
     * opaque failure and a rollback.
     *
     * @return list<string>
     */
    private function uploadLogo(Campaign $campaign, GoogleAdsConnection $connection): array
    {
        $assetId = $campaign->meta['google_logo_asset_id'] ?? null;
        $asset = filled($assetId) ? Asset::find($assetId) : null;
        $disk = $asset === null ? null : Storage::disk($asset->disk ?: 'local');

        if ($asset === null || $asset->kind !== 'image' || ! $disk->exists($asset->path)) {
            throw new RuntimeException(
                'This Performance Max campaign has no brand logo. Google will not run an asset group '
                .'without one. Ask which of the attached squares is the logo and record it with '
                .'attach_creatives, or upload one. Nothing was created.'
            );
        }

        $contents = $disk->get($asset->path);
        $size = @getimagesizefromstring($contents);

        if (! is_array($size) || $size[0] !== $size[1] || $size[0] < 128) {
            throw new RuntimeException(sprintf(
                'The creative named as the logo is %s, and Google needs a square of at least 128x128. '
                .'Nothing was created.',
                is_array($size) ? $size[0].'x'.$size[1] : 'not a readable image',
            ));
        }

        return [$this->google->createImageAsset($connection, $contents, $asset->original_name ?: $campaign->name.' logo')];
    }

    /**
     * One shape's images, uploaded to the account.
     *
     * @param  list<array{contents: string, name: string}>  $images
     * @return list<string>
     */
    private function uploadImages(GoogleAdsConnection $connection, array $images): array
    {
        $resources = [];

        foreach ($images as $image) {
            $resources[] = $this->google->createImageAsset($connection, $image['contents'], $image['name']);
        }

        return array_values(array_unique($resources));
    }

    /**
     * Countries as Google's own geo target resources.
     *
     * @return list<string>
     */
    private function locations(Campaign $campaign): array
    {
        $codes = $this->selections->countries($campaign);
        $targets = $this->selections->googleGeoTargets($campaign);

        $this->countries->resolve('google', $codes, $campaign->ad_account_id);
        $wholeCountries = $targets['countries'] === []
            ? []
            : $this->countries->resolve('google', $targets['countries'], $campaign->ad_account_id);

        return array_values(array_unique([...$wholeCountries, ...$targets['geo_targets']]));
    }

    /**
     * Ad copy gathered across every ad, deduplicated.
     *
     * Meta runs one creative per ad; a Google responsive search ad is one ad
     * holding many headlines that Google combines itself. So the copy written
     * for several Meta ads becomes the variations inside a single Google one,
     * which is the same words used the way each platform uses them.
     *
     * @param  Collection<int, CampaignAd>  $ads
     * @return list<string>
     */
    /**
     * The ad assets the buyer approved, and only those.
     *
     * Each is intersected with what the page currently proposes, for the same
     * reason the copy lines are: a selection made before the page was
     * re-analysed must narrow the candidates rather than resurrect ones that no
     * longer exist. An approval of something the page no longer offers is not
     * an approval of anything.
     *
     * Absent means absent. Unlike the copy lines there is no fallback to "all
     * of them", because an ad with no sitelinks is a perfectly good ad and an
     * ad with sitelinks nobody chose is the defect this exists to stop.
     *
     * @return array{sitelinks: list<array{text: string, final_url: string}>, callouts: list<string>, structured_snippet: array{header: string, values: list<string>}|null}
     */
    private function approvedAssets(Campaign $campaign): array
    {
        $assets = app(GoogleAdAssets::class);
        $analysis = $campaign->brief?->pageAnalysis();
        $approved = (array) ($campaign->meta['google_ad_assets'] ?? []);

        $keptSitelinks = array_map('strval', (array) ($approved['sitelinks'] ?? []));
        $keptCallouts = array_map('strval', (array) ($approved['callouts'] ?? []));

        return [
            'sitelinks' => $keptSitelinks === [] ? [] : array_values(array_filter(
                $assets->sitelinksFor($analysis),
                static fn (array $sitelink): bool => in_array($sitelink['text'], $keptSitelinks, true),
            )),
            'callouts' => $keptCallouts === [] ? [] : array_values(array_intersect(
                $assets->calloutsFor($analysis),
                $keptCallouts,
            )),
            // The snippet is one thing rather than a list, so approving it is a
            // yes to the header the page implied.
            'structured_snippet' => ($approved['structured_snippet'] ?? false)
                ? $assets->structuredSnippetFor($analysis, $campaign->meta['google_snippet_header'] ?? null)
                : null,
        ];
    }

    /**
     * The lines the buyer ticked, or all of them if they have not been asked.
     *
     * Intersected rather than trusted, and in the written order rather than the
     * clicked order: copy regenerated after the selection was made would
     * otherwise publish lines that no longer exist, and a stale selection must
     * narrow the set rather than replace it.
     *
     * A selection that no longer leaves enough lines is discarded rather than
     * honoured. choose_ad_copy will not record fewer than Google's minimum, but
     * regenerating the copy afterwards can strand a selection that was valid
     * when it was made, and honouring three stale headlines out of fifteen
     * fresh ones would meet TOO_FEW at publish with the campaign already built.
     * Everything written is the safe fallback: it is what would have published
     * before the buyer was ever asked.
     *
     * @param  list<string>  $written
     * @return list<string>
     */
    private function keptLines(Campaign $campaign, string $key, array $written, int $least): array
    {
        $kept = (array) (($campaign->meta['google_copy_lines'] ?? [])[$key] ?? []);

        if ($kept === []) {
            return $written;
        }

        $narrowed = array_values(array_intersect($written, array_map('strval', $kept)));

        return count($narrowed) >= $least ? $narrowed : $written;
    }

    private function copy($ads, string ...$fields): array
    {
        return $ads
            ->flatMap(fn ($ad): array => array_map(fn (string $field): ?string => $ad->{$field}, $fields))
            ->filter(fn (?string $text): bool => filled($text))
            ->map(fn (string $text): string => trim($text))
            ->unique()
            ->values()
            ->all();
    }

    /**
     * Send approved changes to the live Google campaign.
     *
     * Nothing did this before: CampaignUpdater sent every platform's edits to
     * Meta, so a Google campaign's changes went to the Graph API carrying a
     * Google customer id and Google object ids, and were then recorded as
     * applied because the snapshot moves on success.
     *
     * Only the fields GoogleRules declares editable can arrive here, and every
     * one of them is handled. A field it claimed but this ignored would leave
     * the campaign and the platform disagreeing while our snapshot said they
     * matched, which is the failure the interface warns about.
     *
     * @param  array<string, array{from: mixed, to: mixed}>  $changes
     */
    public function update(Campaign $campaign, array $changes, string $actor): void
    {
        $connection = GoogleAdsConnection::shared()
            ?? throw new RuntimeException(GoogleAdsConnection::missingReason());

        $ids = (array) ($campaign->external_ids ?? []);
        $campaignId = (string) ($ids['campaign_id'] ?? $campaign->external_campaign_id);

        if ($campaignId === '') {
            throw new RuntimeException('This campaign has no Google campaign id, so there is nothing to update.');
        }

        $fields = [];

        if (array_key_exists('name', $changes)) {
            $fields['name'] = (string) $changes['name']['to'];
        }

        // Read off the model rather than the diff: the diff holds normalised
        // comparison strings, and these need the real dates and the real
        // numbers. Bidding is sent whole because the strategy and its target
        // are one block to Google, and half of it is not a valid campaign.
        if (array_key_exists('starts_at', $changes)) {
            $fields['startDateTime'] = $campaign->starts_at?->format('Y-m-d 00:00:00');
        }

        if (array_key_exists('ends_at', $changes)) {
            $fields['endDateTime'] = $campaign->ends_at?->format('Y-m-d 23:59:59');
        }

        if (array_key_exists('bid_strategy', $changes) || array_key_exists('bid_amount', $changes)) {
            $fields = [
                ...$fields,
                // The channel decides where the target lives, so an edit has to
                // say which channel it is editing or it sends Search the shape
                // only Display accepts.
                ...$this->google->biddingFor(
                    (string) $campaign->bid_strategy,
                    $campaign->bid_amount !== null ? (float) $campaign->bid_amount : null,
                    $this->google->channelFor($campaign->campaign_type),
                ),
            ];
        }

        // Networks are campaign fields, so they move with the rest. Sent whole
        // for the same reason as bidding: Google reads the block, and naming
        // one network in the mask would clear the others.
        if (array_key_exists('placements', $changes)) {
            $fields['networkSettings'] = $this->google->networksFor(
                array_values((array) ($campaign->placements ?? [])),
                ['targetGoogleSearch' => true, 'targetSearchNetwork' => false, 'targetContentNetwork' => false],
            );
        }

        // The money is its own resource. An adopted campaign without its budget
        // id must fail rather than report an update Google never received.
        if (array_key_exists('budget', $changes) && blank($ids['budget_id'] ?? null)) {
            throw new RuntimeException('The Google budget id is missing; refresh this campaign before editing its budget.');
        }

        if (array_key_exists('budget', $changes)
            && array_key_exists('budget_reference_count', $ids)
            && $ids['budget_reference_count'] !== 1) {
            throw new RuntimeException('This Google budget may be shared by multiple campaigns and cannot be edited here.');
        }

        if (array_key_exists('budget', $changes) && array_key_exists('budget_reference_count', $ids)) {
            $profile = $this->google->readCampaignProfile($connection, $campaignId, fresh: true);
            $expectedBudget = 'customers/'.str_replace('-', '', (string) $connection->customer_id).'/campaignBudgets/'.$ids['budget_id'];

            if ($profile['id'] !== $campaignId
                || $profile['budget_resource'] !== $expectedBudget
                || $profile['budget_reference_count'] !== 1) {
                throw new RuntimeException('Google budget ownership changed since import. Refresh this campaign before editing its budget.');
            }
        }

        // A null date is the change, not a missing value.
        //
        // array_filter dropped both date keys whenever the buyer cleared one,
        // and updateLiveCampaign returns early on an empty set, so "drop the
        // end date and let it keep running" made no call at all - while
        // CampaignUpdater went on to write the new published_state and mark the
        // change applied. The campaign stopped serving on its old end date and
        // our record said it had none. Google clears a field by carrying it in
        // the update mask with a null value, which is what MetaPublisher has
        // always done, so the dates are kept and only genuinely absent fields
        // are filtered out.
        $dateFields = ['startDateTime', 'endDateTime'];

        $this->google->updateLiveCampaign($connection, $campaignId, array_filter(
            $fields,
            fn (mixed $value, string $key): bool => $value !== null || in_array($key, $dateFields, true),
            ARRAY_FILTER_USE_BOTH,
        ));

        if (array_key_exists('budget', $changes)) {
            $this->google->updateLiveBudget($connection, (string) $ids['budget_id'], (float) $campaign->budget);
        }
    }

    /**
     * Start the campaign, and its children only if none of them are running.
     *
     * Google's word for live is ENABLED. The ad group, the ad and a Performance
     * Max asset group each carry their own status and are all created PAUSED, so
     * enabling the campaign alone produces a campaign that is live and serves
     * nothing - which is why this enables every level, and is still the right
     * thing on a first activation.
     *
     * The asset group was the level that had no write path at all, so a
     * Performance Max campaign was enabled at the campaign and left switched
     * off everywhere that could serve, while isLive() read the campaign as
     * ENABLED and called it live.
     *
     * It was wrong on every activation after that. pause() deliberately stops
     * at the campaign, so pausing and restarting was not symmetric: an ad group
     * or ad somebody had paused on purpose came back enabled, and nothing said
     * so. A buyer who had turned off one of three ads and then paused and
     * restarted the campaign was spending on the ad they had switched off.
     *
     * So the children are enabled only when nothing among them is already
     * enabled, which is what a campaign straight out of publishing looks like.
     * Meta guards the same thing the same way, in nothingIsRunning().
     */
    public function activate(Campaign $campaign, string $actor): void
    {
        $ids = $this->ids($campaign);

        $this->google->setLiveStatus(
            $this->connection($campaign),
            $this->nothingIsRunning($campaign)
                ? $ids
                : ['campaign_id' => $ids['campaign_id'] ?? null],
            'ENABLED',
        );
    }

    /**
     * Whether Google reports nothing under this campaign as enabled.
     *
     * Fails towards the old behaviour, as Meta's equivalent does: if the read
     * fails there is no evidence anything is running, and a campaign that will
     * not serve is a worse outcome than one that restarts a child somebody had
     * paused.
     *
     * Asset groups are counted too. Performance Max keeps its creative there
     * and has no ad groups, so reading only those would call every live PMax
     * campaign idle.
     */
    private function nothingIsRunning(Campaign $campaign): bool
    {
        try {
            $structure = $this->google->readCampaignStructure(
                $this->connection($campaign),
                (string) $this->ids($campaign)['campaign_id'],
            );
        } catch (Throwable $e) {
            Log::warning('Could not read child statuses before activating a Google campaign', [
                'campaign' => $campaign->id, 'error' => $e->getMessage(),
            ]);

            return true;
        }

        foreach ([...$structure['ad_groups'], ...$structure['ads'], ...$structure['asset_groups']] as $child) {
            if (($child['status'] ?? '') === 'ENABLED') {
                return false;
            }
        }

        return true;
    }

    /** And stop it at the campaign, which is where delivery is decided. */
    public function pause(Campaign $campaign, string $actor): void
    {
        $ids = $this->ids($campaign);

        $this->google->setLiveStatus(
            $this->connection($campaign),
            ['campaign_id' => $ids['campaign_id'] ?? null],
            'PAUSED',
        );
    }

    /**
     * What Google says the campaign's state is.
     *
     * `fresh: true` is not optional here. readCampaignProfile() and the search
     * beneath it both default to a cache with a day's life, so without it this
     * answers from a reading that may predate the question by hours - which is
     * the same stale-state mistake asking the platform is meant to avoid. It
     * cost a full cleanup run to learn that once already.
     */
    public function isLive(Campaign $campaign, string $actor): ?bool
    {
        try {
            $profile = $this->google->readCampaignProfile(
                $this->connection($campaign),
                (string) $this->ids($campaign)['campaign_id'],
                fresh: true,
            );
        } catch (Throwable $e) {
            Log::warning('Could not read campaign status from Google Ads', [
                'campaign' => $campaign->id, 'error' => $e->getMessage(),
            ]);

            return null;
        }

        $status = strtoupper((string) ($profile['status'] ?? ''));

        return $status === '' ? null : $status === 'ENABLED';
    }

    /**
     * The ids recorded when the campaign was built.
     *
     * external_campaign_id is the fallback for the campaign itself, because an
     * adopted campaign has one without ever having had an external_ids map.
     *
     * @return array<string, mixed>
     */
    private function ids(Campaign $campaign): array
    {
        $ids = (array) ($campaign->external_ids ?? []);
        $campaignId = (string) ($ids['campaign_id'] ?? $campaign->external_campaign_id);

        if ($campaignId === '') {
            throw new RuntimeException('This campaign has no Google campaign id, so there is nothing to start.');
        }

        return [...$ids, 'campaign_id' => $campaignId];
    }
}
