<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\CampaignApprovalBinding;
use App\Campaigns\LinkedInManagement;
use App\Campaigns\Meta\AdSetEditGuard;
use App\Campaigns\PendingChanges;
use App\Campaigns\Publishing\MetaPublisher;
use App\Campaigns\Targeting\SearchKeywordSelections;
use App\Models\Asset;
use App\Models\Campaign;
use App\Models\CampaignAdSet;
use App\Models\CampaignChange;
use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use App\Services\Platforms\Support\Guardrails;
use App\Support\Actor;
use App\Support\CurrencyMinorUnits;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Approvals\Approval;
use Laravel\Ai\Concerns\InteractsWithApprovals;
use Laravel\Ai\Contracts\Approvable;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;
use Throwable;

/**
 * Change one ad set or one ad that is already on the platform.
 *
 * push_changes could only ever edit the campaign and its *first* ad set, because
 * it works by diffing the campaign's own attributes against the snapshot taken
 * at publish - and a campaign has one budget, one bid and one schedule however
 * many ad sets hang off it. A second ad set's settings had nowhere to be
 * expressed, so they could not be changed at all. The rows have carried their
 * own budget, bid, schedule and name since 5 Oct; nothing could reach them.
 *
 * This addresses an object by id instead of diffing, so every ad set is equal.
 * It does not replace push_changes, which still owns campaign-level edits and
 * the things that need a rebuild rather than an update.
 *
 * Always approval-gated, because push_changes is: editing a live ad set's budget
 * or bid changes what somebody spends, and that is the line approvals exist on.
 *
 * It also goes through assertChangeAllowed(), so the change cooldown and the
 * daily cap apply here exactly as they do to a campaign edit. Those exist to
 * stop a disagreeing user and model, or a retry loop, rewriting a live object
 * repeatedly, and addressing objects individually would otherwise be a way
 * around them.
 */
class EditEntity implements Approvable, Tool
{
    use ActsOnFocusedCampaign, InteractsWithApprovals;

    /**
     * What Meta will change in place, and what this will send.
     *
     * Deliberately short. Targeting is left to the published-location tools,
     * which carry the verified-place machinery this would have to duplicate;
     * copy and creative are a new creative and a repointed ad rather than an
     * edit; and optimization_goal and billing_event reset or refuse mid-flight,
     * so they are a rebuild decision rather than a field to type over.
     */
    private const AD_SET_FIELDS = [
        'name', 'budget', 'bid_strategy', 'bid_amount', 'starts_at', 'ends_at',
        'daily_min_spend_target', 'daily_spend_cap', 'lifetime_min_spend_target', 'lifetime_spend_cap',
        'budget_schedule_specs', 'roas_average_floor', 'pacing_type', 'adset_schedule', 'targeting',
        'conversion_event', 'frequency_control_specs', 'value_rule_set_id', 'value_rules_applied',
    ];

    /**
     * Copy is editable, by replacing the creative under the same ad.
     *
     * Meta cannot reword a creative, but it will point an existing ad at a new
     * one - which keeps the ad's id and history where adding a second ad beside
     * it would not. The old refusal treated the creative's immutability as the
     * ad's.
     */
    private const AD_FIELDS = ['name', 'headline', 'primary_text', 'description', 'cta', 'asset_id'];

    /**
     * What a Google ad group can actually be told to change.
     *
     * No budget and no bid strategy, because an ad group holds neither on
     * Google - the campaign does. Those are not missing here, they are
     * questions with no answer at this level.
     *
     * Keywords are here because nothing else could reach them once a campaign
     * was live: SearchKeywordSelections::save refuses a published campaign, and
     * every other write to adGroupCriteria is inside the publish path.
     */
    private const GOOGLE_AD_GROUP_FIELDS = ['name', 'cpc_bid', 'keywords'];

    /**
     * The ones that live inside the creative, so changing any of them means
     * building a new creative rather than updating a field.
     *
     * The image is here for the same reason the wording is: creative() builds
     * the spec from the ad's own asset, so pointing the ad at a different
     * uploaded asset and rebuilding is all a swap takes.
     */
    private const CREATIVE_FIELDS = ['headline', 'primary_text', 'description', 'cta', 'asset_id'];

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Meta $meta,
        private readonly Guardrails $guardrails,
        private readonly PendingChanges $pending,
        private readonly MetaPublisher $metaPublisher,
        private readonly Actor $actor,
        private readonly CampaignApprovalBinding $approvalBinding,
        private readonly AdSetEditGuard $guard,
    ) {}

    public function description(): Stringable|string
    {
        return 'Change a specific ad set or ad that is already live on Meta, a Google ad group, or '
            .'rename a LinkedIn creative/ad or campaign_group. On Meta: rename an ad set, or change '
            .'its budget, bid strategy, bid amount, ROAS goal, pacing, start date or end date, its '
            .'campaign-budget spend limits, its budget schedule, the hours it runs, its audience, including a country, state, city, or ZIP, its placements, its devices, its conversion event, a reach frequency cap, or a value rule. A live location change sends every key chosen from list_live_locations, in one targeting.geo_locations. Do not guess a region or city key. A state or city is sent alone, without the country. It works on any ad set, not '
            .'just the first. On Google: rename an ad group, change its CPC bid, or change its '
            .'keywords and their match types on a campaign that is already running - a Google ad '
            .'cannot be edited in place, and budget and bid strategy live on the campaign there. On '
            .'LinkedIn: copy/image changes stage a DRAFT replacement, leaving the original '
            .'unchanged; separately approved activation swaps it and pauses the original. Needs the '
            .'id from list_campaign_structure, or the ad set\'s current name. Pass campaign_id when the user names a campaign, and use '
            .'that campaign even when the ad is not stored here. The user approves it. For campaign-level settings use '
            .'push_changes. On Meta, new copy or a different uploaded image is applied by building a '
            .'new creative under the same ad, so the ad keeps its id and history - Meta restarts the '
            .'learning phase when that happens.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'entity_type' => $schema->string()->enum(['ad_set', 'ad_group', 'ad', 'creative', 'campaign_group'])
                ->description('Which level to change. ad_set is Meta\'s word and ad_group is Google\'s; '
                    .'either is accepted for that level. creative and campaign_group are LinkedIn\'s.')
                ->required(),
            'id' => $schema->string()
                ->description('An ad set\'s platform id or its current name. An ad, creative, or campaign group needs its platform id.')
                ->required(),
            'name' => $schema->string()->description('A new name for it.'),
            'cpc_bid' => $schema->number()->description('Google ad group only. The new default CPC bid, '
                .'in the account currency. Budget and bid strategy live on the campaign on Google.'),
            'keywords' => $schema->array()->items($schema->object([
                'text' => $schema->string()->required(),
                'match_type' => $schema->string()->description('BROAD, PHRASE, or EXACT.')->required(),
                'negative' => $schema->boolean()->description('True to exclude searches matching this term.'),
            ]))->description('Google ad group only. The complete keyword set this ad group should end up '
                .'with, not just the changes. Terms already on it are left untouched so they keep their '
                .'history; anything missing from this list is removed. Read the current set from '
                .'list_campaign_structure or ask before replacing it.'),
            'budget' => $schema->number()->description('Ad set only. The new amount, in the account currency.'),
            'bid_strategy' => $schema->string()->description('Ad set only. One of the campaign\'s supported bid strategies. Highest volume is LOWEST_COST_WITHOUT_CAP. Do not pass a bid amount. This tool clears the bid amount already on the ad set in the same request, including after an earlier attempt failed.'),
            'bid_amount' => $schema->number()->description('Ad set only. The new bid cap or cost per result goal, in the account currency. A cost cap or bid cap already on the ad set is sent with it.'),
            'starts_at' => $schema->string()->description('Ad set only. New start, as a date or date and time.'),
            'ends_at' => $schema->string()->description('Ad set only. New end, as a date or date and time.'),
            'daily_min_spend_target' => $schema->number()->description('Ad set only, and only when the campaign holds the budget. Minimum daily spend, in the account currency.'),
            'daily_spend_cap' => $schema->number()->description('Ad set only, and only when the campaign holds the budget. Maximum daily spend, in the account currency.'),
            'lifetime_min_spend_target' => $schema->number()->description('Ad set only, and only when the campaign holds the budget. Minimum lifetime spend, in the account currency.'),
            'lifetime_spend_cap' => $schema->number()->description('Ad set only, and only when the campaign holds the budget. Maximum lifetime spend, in the account currency.'),
            'budget_schedule_specs' => $schema->array()->items($schema->object([
                'time_start' => $schema->string()->description('When this higher budget starts.')->required(),
                'time_end' => $schema->string()->description('When this higher budget ends.')->required(),
                'budget_value' => $schema->number()->description('ABSOLUTE amount in the account currency, or a MULTIPLIER percentage.')->required(),
                'budget_value_type' => $schema->string()->description('ABSOLUTE or MULTIPLIER. Defaults to ABSOLUTE.'),
            ]))->description('Ad set only. The complete budget schedule, replacing whatever is set. Pass an empty list to clear it. This is a temporary budget change, not dayparting.'),
            'roas_average_floor' => $schema->number()->description('Ad set only. The minimum ROAS goal, such as 2.5. Only when the bid strategy is LOWEST_COST_WITH_MIN_ROAS.'),
            'pacing_type' => $schema->string()->enum(['standard', 'no_pacing', 'day_parting'])
                ->description('Ad set only. standard is even pacing. no_pacing is accelerated and only works with a bid cap. day_parting is required for an hourly schedule.'),
            'adset_schedule' => $schema->array()->items($schema->object([
                'days' => $schema->array()->items($schema->integer())->description('0 is Sunday through 6 is Saturday.')->required(),
                'start_minute' => $schema->integer()->description('Minutes from midnight when delivery starts.')->required(),
                'end_minute' => $schema->integer()->description('Minutes from midnight when delivery ends. 1440 is the end of the day.')->required(),
                'timezone_type' => $schema->string()->description('USER or ADVERTISER. Defaults to ADVERTISER.'),
            ]))->description('Ad set only. The complete dayparting schedule, replacing whatever is set. Pass an empty list to clear it. Only on an ad set with its own lifetime budget.'),
            'targeting' => $schema->object([
                'geo_locations' => $schema->object([
                    'countries' => $schema->array()->items($schema->string()),
                    'regions' => $schema->array(),
                    'cities' => $schema->array(),
                    'zips' => $schema->array(),
                    'location_types' => $schema->array()->items($schema->string())->description('home, recent, or travel.'),
                ])->description('Replaces the whole location. Include every place the ad set should keep.'),
                'excluded_geo_locations' => $schema->object([
                    'countries' => $schema->array()->items($schema->string()),
                    'regions' => $schema->array(),
                    'cities' => $schema->array(),
                    'zips' => $schema->array(),
                ])->description('Places to exclude. An empty object clears them.'),
                'age_min' => $schema->integer()->description('18 to 65.'),
                'age_max' => $schema->integer()->description('18 to 65.'),
                'genders' => $schema->array()->items($schema->integer())->description('1 male, 2 female. An empty list reaches everyone.'),
                'locales' => $schema->array()->description('Language names or the locale numbers from search_ad_locales. An empty list clears them. Do not invent a number.'),
                'custom_audiences' => $schema->array()->description('Audience ids, including lookalikes. An empty list clears them.'),
                'excluded_custom_audiences' => $schema->array()->description('Audience ids to exclude. An empty list clears them.'),
                'flexible_spec' => $schema->array()->description('Interests, behaviors, and demographics. Replaces the whole list. An empty list clears it.'),
                'exclusions' => $schema->object([])->description('Interests, behaviors, or demographics to exclude. An empty object clears them.'),
                'advantage_audience' => $schema->integer()->description('0 keeps the audience as set. 1 lets Meta expand it.'),
                'targeting_relaxation_types' => $schema->object([
                    'lookalike' => $schema->integer()->description('0 or 1.'),
                    'custom_audience' => $schema->integer()->description('0 or 1.'),
                ]),
                'advantage_placements' => $schema->boolean()->description('True uses Advantage+ placements and clears every manual platform and position.'),
                'publisher_platforms' => $schema->array()->items($schema->string())->description('facebook, instagram, audience_network, messenger, or threads. Replaces the whole platform list. An empty list switches to Advantage+ placements.'),
                'facebook_positions' => $schema->array()->items($schema->string())->description('feed, story, facebook_reels, marketplace, or search.'),
                'instagram_positions' => $schema->array()->items($schema->string())->description('stream, story, or reels. stream is the feed and is required with Threads.'),
                'audience_network_positions' => $schema->array()->items($schema->string())->description('classic or rewarded_video.'),
                'messenger_positions' => $schema->array()->items($schema->string())->description('messenger_home or story.'),
                'threads_positions' => $schema->array()->items($schema->string())->description('threads_stream. Threads also requires the Instagram feed.'),
                'device_platforms' => $schema->array()->items($schema->string())->description('mobile or desktop. An empty list reaches every device.'),
                'user_os' => $schema->array()->items($schema->string())->description('iOS or Android, optionally with a version such as iOS_ver_14.0_and_above. Mobile only. An empty list clears it.'),
                'user_device' => $schema->array()->items($schema->string())->description('Device names Meta uses, such as iPhone or iPad. Mobile only. An empty list clears them.'),
                'excluded_user_device' => $schema->array()->items($schema->string())->description('Device names to exclude. Mobile only. An empty list clears them.'),
                'wireless_carrier' => $schema->array()->items($schema->string())->description('Wifi only. Mobile only. An empty list clears it.'),
            ])->description('Ad set only. Pass only the audience, placement, or device fields to change. The current targeting is read and merged. Read it with read_delivery first.'),
            'conversion_event' => $schema->string()->description('Ad set only. A Meta event such as PURCHASE. The pixel already on the ad set is kept.'),
            'frequency_control_specs' => $schema->array()->items($schema->object([
                'event' => $schema->string()->description('IMPRESSIONS.')->required(),
                'interval_days' => $schema->integer()->description('1 to 90.')->required(),
                'max_frequency' => $schema->integer()->description('How many times a person can be reached in that interval.')->required(),
            ]))->description('Ad set only, and only when it optimizes for reach. The complete frequency cap. An empty list clears it.'),
            'value_rule_set_id' => $schema->string()->description('Ad set only. The id of a value rule set. Only with highest volume or cost cap.'),
            'value_rules_applied' => $schema->boolean()->description('Ad set only. False detaches the value rule. Do not send an id in the same change.'),
            'headline' => $schema->string()->description('Ad only. New headline. Replaces the creative under the same ad.'),
            'primary_text' => $schema->string()->description('Ad only. New body text. Replaces the creative under the same ad.'),
            'description' => $schema->string()->description('Ad only. New description line.'),
            'cta' => $schema->string()->description('Ad only. New call-to-action button.'),
            'asset_id' => $schema->integer()->description('Ad only. A different image or video, by asset id, '
                .'from one already uploaded in this conversation. Replaces the creative under the same ad.'),
            'campaign_id' => $schema->string()->description('The Meta campaign id the user named. Pass it when '
                .'they give a campaign id, including for an ad that is not stored in this workspace.'),
        ];
    }

    /**
     * Always, for the same reason push_changes always does: this changes spending.
     *
     * A live Meta ad set is checked first. An edit Meta will refuse does not
     * get an approval card. One that can reset learning says so on the card.
     */
    protected function needsApproval(Request $request): Approval|bool
    {
        $campaign = $this->focused();
        $note = null;

        if ($campaign !== null && $campaign->platform === 'meta' && $campaign->isPublished()) {
            $arguments = $request->all();
            $type = (string) ($arguments['entity_type'] ?? '');
            $id = trim((string) ($arguments['id'] ?? ''));

            if (($type === 'ad_set' || $type === 'ad_group') && $id !== '') {
                $resolved = $this->resolveAdSet($campaign, $id);

                if (isset($resolved['error'])) {
                    return false;
                }

                $id = $resolved['id'];
                $given = $this->givenAdSetFields($arguments);
                $review = $this->guard->review(
                    $campaign,
                    $id,
                    $campaign->adSets()->where('external_adset_id', $id)->first(),
                    $given,
                    $arguments,
                );

                if ($review['ok'] === false) {
                    return false;
                }

                $noteParts = [$this->adSetNote($resolved)];

                if (array_key_exists('bid_amount', $given)) {
                    $noteParts[] = 'Cost per result goal '.$this->amountLabel((float) $given['bid_amount'], $campaign->currency).'.';
                }

                if ($review['warnings'] !== []) {
                    $noteParts[] = implode(' ', $review['warnings']);
                }

                $note = implode(' ', $noteParts);
            }
        }

        return $this->approvalBinding->request($request, $campaign, 'edit_entity', note: $note);
    }

    public function handle(Request $request): Stringable|string
    {
        if (! $campaign = $this->focused()) {
            return $this->noCampaign();
        }

        $arguments = $request->all();
        $type = (string) ($arguments['entity_type'] ?? '');
        $id = trim((string) ($arguments['id'] ?? ''));

        // ad_group is Google's word for the level ad_set names on Meta. LinkedIn
        // never sends it, so normalising before the shared check is safe.
        $type = $type === 'ad_group' ? 'ad_set' : $type;

        if (! in_array($type, ['ad_set', 'ad', 'creative', 'campaign_group'], true) || $id === '') {
            return $this->json([
                'ok' => false,
                'error' => 'Choose ad_set, ad, creative, or campaign_group and give its exact live ID. LinkedIn supports ad, creative, and campaign_group; Meta supports ad_set and ad.',
            ]);
        }

        if ($campaign->platform === 'linkedin') {
            $fields = array_filter(array_diff_key($arguments, array_flip(['entity_type', 'id'])),
                static fn (mixed $value): bool => $value !== null && $value !== '');
            $record = null;
            try {
                $actor = $this->actor->describe();
                $management = app(LinkedInManagement::class);
                $management->entity($campaign, $type, $id, $actor);
                $this->guardrails->assertChangeAllowed($campaign->id);
                $record = CampaignChange::create(['campaign_id' => $campaign->id, 'actor' => $actor,
                    'changes' => [$type.':'.$id => $fields], 'state' => 'pending']);
                $result = $management->update($campaign, $type, $id, $fields, $actor);
                $record->update(['state' => 'applied', 'applied_at' => now()]);

                return $this->json(['ok' => true, ...$result]);
            } catch (Throwable $exception) {
                $record?->update(['state' => 'failed', 'error' => $exception->getMessage()]);

                return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
            }
        }

        if ($campaign->platform === 'google') {
            return $this->handleGoogle($campaign, $type, $id, $arguments);
        }

        if ($campaign->platform !== 'meta') {
            return $this->json([
                'ok' => false,
                'error' => sprintf('Editing a single ad set or ad is only available on Meta and Google. This campaign is on %s.', ucfirst((string) $campaign->platform)),
            ]);
        }

        if (! in_array($type, ['ad_set', 'ad'], true)) {
            return $this->json(['ok' => false, 'error' => 'Meta supports ad_set and ad here.']);
        }

        if (! $campaign->isPublished()) {
            return $this->json([
                'ok' => false,
                'error' => 'This campaign has not been published, so there is nothing on Meta to change. Change the draft instead.',
            ]);
        }

        $allowed = $type === 'ad_set' ? self::AD_SET_FIELDS : self::AD_FIELDS;
        $given = array_intersect_key($arguments, array_flip($allowed));
        $given = array_filter($given, static fn (mixed $value): bool => $value !== null && $value !== '');

        if (($given['targeting'] ?? null) === []) {
            unset($given['targeting']);
        }

        // Named rather than ignored. Silently dropping a field the buyer asked
        // for and then reporting success is how an edit gets believed without
        // having happened.
        if ($refused = array_diff(array_keys(array_filter($arguments, static fn (mixed $v): bool => $v !== null && $v !== '')), [...$allowed, 'entity_type', 'id', 'campaign_id'])) {
            if ($type === 'ad_set' && array_intersect($refused, AdSetEditGuard::LOCKED) !== []) {
                $review = $this->guard->review($campaign, $id, $campaign->adSets()->where('external_adset_id', $id)->first(), $given, $arguments);

                return $this->json([
                    'ok' => false,
                    'error' => $review['error'],
                    'locked' => $review['locked'],
                    'note' => 'These fields are fixed once the ad set exists. Quote the live value and do not try the edit again.',
                ]);
            }

            return $this->json([
                'ok' => false,
                'error' => sprintf('%s cannot be changed on an %s after publishing.', implode(', ', $refused), str_replace('_', ' ', $type)),
                'note' => $type === 'ad' && array_intersect($refused, ['body', 'creative', 'image', 'asset'])
                    ? 'Copy and the image are changed by name: headline, primary_text, description, cta, asset_id. '
                        .'Use those rather than this field name.'
                    : 'Say which field cannot change and do not offer to try it again.',
            ]);
        }

        if ($given === []) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('Nothing to change. On an %s this can change: %s.', str_replace('_', ' ', $type), implode(', ', $allowed)),
            ]);
        }

        $namedCampaign = trim((string) ($arguments['campaign_id'] ?? ''));

        if ($type === 'ad' && $namedCampaign !== '') {
            $local = $campaign->ads()->where('external_ad_id', $id)->first();
            $sameCampaign = $namedCampaign === (string) $campaign->external_campaign_id;

            if ($local === null || ! $sameCampaign) {
                return $this->rewriteUnstoredAd($campaign, $id, $namedCampaign, $given);
            }
        }

        if ($type === 'ad_set') {
            $resolved = $this->resolveAdSet($campaign, $id);

            if (isset($resolved['error'])) {
                return $this->json([
                    'ok' => false,
                    'error' => $resolved['error'],
                    'note' => 'Nothing was changed.',
                ]);
            }

            $id = $resolved['id'];
        }

        try {
            if (! in_array($id, $this->idsUnder($campaign, $type), true)) {
                return $this->json([
                    'ok' => false,
                    'error' => sprintf('%s is not in this campaign, so nothing was changed.', $id),
                    'note' => 'Call list_campaign_structure for the current ids.',
                ]);
            }

            $this->guardrails->assertChangeAllowed($campaign->id);
        } catch (MetaException $e) {
            return $this->json(['ok' => false, 'error' => $e->getMessage()]);
        }

        $copy = array_intersect_key($given, array_flip(self::CREATIVE_FIELDS));

        if ($copy !== []) {
            return $this->rebuildTheCreative($campaign, $id, $given, $copy);
        }

        $row = $type === 'ad_set'
            ? $campaign->adSets()->where('external_adset_id', $id)->first()
            : null;
        $warnings = [];

        if ($type === 'ad_set') {
            $review = $this->guard->review($campaign, $id, $row, $given, $arguments);

            if ($review['ok'] === false) {
                return $this->json([
                    'ok' => false,
                    'error' => $review['error'],
                    'locked' => $review['locked'],
                    'note' => 'Nothing was changed.',
                ]);
            }

            $warnings = $review['warnings'];
        }

        try {
            $fields = $this->platformFields($campaign, $row, $type, $given, $id);
        } catch (Throwable $e) {
            return $this->json(['ok' => false, 'error' => $e->getMessage()]);
        }

        $record = CampaignChange::create([
            'campaign_id' => $campaign->id,
            'actor' => $this->actor->describe(),
            'changes' => [$type.':'.$id => $given],
            'state' => 'pending',
        ]);

        try {
            $this->meta->on($campaign->id, $this->actor->describe())
                ->updateEntity($campaign->ad_account_id, $id, $type, $fields);
        } catch (Throwable $e) {
            $record->update(['state' => 'failed', 'error' => $e->getMessage()]);

            return $this->json([
                'ok' => false,
                'error' => $e->getMessage(),
                'note' => 'Nothing was changed. Say so plainly rather than describing it as partly done.',
            ]);
        }

        $confirmedBid = null;

        if ($type === 'ad_set' && array_key_exists('bid_amount', $given) && ($fields['bid_strategy'] ?? null) !== 'LOWEST_COST_WITHOUT_CAP') {
            $confirmedBid = $this->confirmedBid($campaign, $id, (int) $fields['bid_amount'], (float) $given['bid_amount']);

            if (is_string($confirmedBid)) {
                $record->update(['state' => 'failed', 'error' => $confirmedBid]);

                return $this->json([
                    'ok' => false,
                    'error' => $confirmedBid,
                    'note' => 'Nothing was changed. Say the amount Meta still has, and do not say the new goal was saved.',
                ]);
            }
        }

        $confirmedStrategy = null;

        if ($type === 'ad_set' && ($given['bid_strategy'] ?? null) === 'LOWEST_COST_WITHOUT_CAP') {
            $confirmedStrategy = $this->confirmedHighestVolume($campaign, $id);

            if (is_string($confirmedStrategy)) {
                $record->update(['state' => 'failed', 'error' => $confirmedStrategy]);

                return $this->json([
                    'ok' => false,
                    'error' => $confirmedStrategy,
                    'note' => 'Nothing was changed. Say the bid strategy Meta still has, and do not say Highest volume was saved.',
                ]);
            }
        }

        $this->recordLocally($campaign, $row, $given);
        $this->forgetStoredError($campaign);
        $record->update(['state' => 'applied', 'applied_at' => now()]);

        $payload = [
            'ok' => true,
            'entity_type' => $type,
            'id' => $id,
            'changed' => $given,
            'learning_warning' => $warnings,
            'note' => sprintf(
                'Changed on Meta: %s. Say what changed in one line.%s%s%s%s',
                implode(', ', array_keys($given)),
                array_key_exists('budget', $given)
                    ? ' This changes what it spends, so say the new figure back.'
                    : '',
                $confirmedBid === null
                    ? ''
                    : ' Meta confirmed the cost per result goal is now '.$this->amountLabel($confirmedBid, $campaign->currency).'. Quote confirmed_bid_amount.',
                $confirmedStrategy === true
                    ? ' Meta confirmed the bid strategy is now Highest volume.'
                    : '',
                $warnings === [] ? '' : ' '.implode(' ', $warnings),
            ),
        ];

        if ($confirmedBid !== null) {
            $payload['confirmed_bid_amount'] = $confirmedBid;
        }

        return $this->json($payload);
    }

    /**
     * New copy or a new image on a live ad: write the row, then put a new
     * creative under it.
     *
     * The row first, because the publisher builds the creative off it - and
     * rolled back if Meta refuses, so a failed edit does not leave our record
     * claiming something the ad does not carry.
     *
     * @param  array<string,mixed>  $given
     * @param  array<string,mixed>  $copy
     */
    /**
     * Rewrite copy on a live ad that this workspace does not have a row for.
     *
     * The campaign id is the one the user named. The creative is read from
     * that ad, the new wording is written onto its story, and the same ad is
     * pointed at the new creative.
     *
     * @param  array<string, mixed>  $given
     */
    private function rewriteUnstoredAd(Campaign $campaign, string $id, string $campaignId, array $given): string
    {
        if (array_key_exists('asset_id', $given)) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('Ad %s is not recorded here, so its image cannot be swapped.', $id),
                'note' => 'Wording can still be changed. Leave the image out of this edit.',
            ]);
        }

        try {
            $result = $this->meta->on($campaign->id, $this->actor->describe())->replaceAdCopy(
                $id,
                $campaignId,
                $campaign->ad_account_id,
                $given,
            );
        } catch (Throwable $exception) {
            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'note' => 'The ad is unchanged and still running its old copy. Say so plainly.',
            ]);
        }

        return $this->json([
            'ok' => true,
            'entity_type' => 'ad',
            'id' => $id,
            'campaign_id' => $campaignId,
            'changed' => $given,
            'creative_id' => $result['creative_id'],
            'note' => 'The ad now runs the new copy under the same ad id, so its history is intact. '
                .'Say what changed in one line, and that Meta restarts the learning phase when an '
                .'ad\'s creative changes, so the next day or so will not compare with the last.',
        ]);
    }

    private function rebuildTheCreative(Campaign $campaign, string $id, array $given, array $copy): string
    {
        $ad = $campaign->ads()->where('external_ad_id', $id)->first();

        if ($ad === null) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('Ad %s is not recorded here, so its copy cannot be rewritten. It may have been created outside this chat.', $id),
                'note' => 'Offer add_ads with the new wording instead, which makes a new ad beside it.',
            ]);
        }

        if (array_key_exists('asset_id', $copy)
            && $refusal = $this->assetIsUnusable($campaign, (int) $copy['asset_id'])) {
            return $refusal;
        }

        $was = $ad->only(self::CREATIVE_FIELDS);

        // Before anything is written. The fingerprint covers every ad at once,
        // so it can only be moved on afterwards if this ad was the only one out
        // of step - otherwise fixing one ad would claim all of them match.
        $theAdsWereInStep = $this->adsMatchThePlatform($campaign);

        $record = CampaignChange::create([
            'campaign_id' => $campaign->id,
            'actor' => $this->actor->describe(),
            'changes' => ['ad:'.$id => $given],
            'state' => 'pending',
        ]);

        $ad->forceFill($copy)->save();

        try {
            $creativeId = $this->metaPublisher->replaceCreative($ad->fresh(), $this->actor->describe());
        } catch (Throwable $e) {
            $ad->forceFill($was)->save();
            $record->update(['state' => 'failed', 'error' => $e->getMessage()]);

            return $this->json([
                'ok' => false,
                'error' => $e->getMessage(),
                'note' => 'The ad is unchanged and still running its old copy. Say so plainly.',
            ]);
        }

        $this->blessTheNewCopy($campaign, $theAdsWereInStep);

        if (array_key_exists('name', $given)) {
            $this->renameAlongside($campaign, $id, (string) $given['name']);
        }

        $record->update(['state' => 'applied', 'applied_at' => now()]);

        return $this->json([
            'ok' => true,
            'entity_type' => 'ad',
            'id' => $id,
            'changed' => $given,
            'creative_id' => $creativeId,
            'note' => 'The ad now runs the new copy under the same ad id, so its history is intact. '
                .'Say what changed in one line, and that Meta restarts the learning phase when an '
                .'ad\'s creative changes, so the next day or so will not compare with the last.',
        ]);
    }

    /**
     * Why this asset cannot back a live ad, if it cannot.
     *
     * Two things have to hold, and neither is checked anywhere downstream.
     * The asset has to be one of this conversation's own, or an id typed into
     * the chat would pull a stranger's upload onto the account. And it has to
     * have been uploaded to this ad account already: creative() reads the
     * account's own hash off the platform ref, so a missing ref is a null
     * dereference inside the publisher rather than an answer anyone can act on.
     */
    private function assetIsUnusable(Campaign $campaign, int $assetId): ?string
    {
        $asset = $this->workspace->artifacts(Asset::class)
            ->map(fn ($link) => $link->artifactable)
            ->filter()
            ->firstWhere('id', $assetId);

        if ($asset === null) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('Asset %d is not attached to this conversation, so it was not used.', $assetId),
                'note' => 'Offer the creatives that are attached, or ask the user to upload the one they mean.',
            ]);
        }

        if ($asset->refFor('meta', (string) $campaign->ad_account_id) === null) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('Asset %d has not been uploaded to %s yet, so the ad was left alone.', $assetId, $campaign->ad_account_id),
                'note' => 'Call review_assets first, which uploads it to the ad account, then try this again.',
            ]);
        }

        return null;
    }

    /**
     * Tell the published snapshot that the live ad now carries this wording.
     *
     * PendingChanges fingerprints every ad's copy at publish time and reports
     * any later difference as "ad copy or creative changed, which needs a new
     * creative and a new ad". That was true until this tool existed. Left
     * alone, a successful copy rewrite would leave the campaign permanently
     * dirty: requiringRebuild would keep naming a change that has already been
     * made, push_changes would refuse every later budget or name edit, and the
     * chat would go on offering a rebuild nobody needs.
     *
     * Only this one key is refreshed, never the whole snapshot. Re-taking the
     * snapshot here would also quietly bless unrelated local drift - a changed
     * landing url or objective - and those genuinely do need a new campaign.
     *
     * And only when the ads were in step to begin with. One fingerprint covers
     * every ad in the campaign, so if write_ad_copy had already rewritten three
     * ads locally, rewriting one of them on Meta and then moving the
     * fingerprint would say all three had been pushed. The rebuild notice has
     * to stand until each one has.
     */
    private function blessTheNewCopy(Campaign $campaign, bool $theAdsWereInStep): void
    {
        if (! $theAdsWereInStep || ! $campaign->isPublished()) {
            return;
        }

        $state = (array) ($campaign->published_state ?? []);

        if (! array_key_exists('ads_fingerprint', $state)) {
            return;
        }

        $state['ads_fingerprint'] = $this->pending->snapshot($campaign->fresh())['ads_fingerprint'];

        $campaign->forceFill(['published_state' => $state])->save();
    }

    /** Whether every ad we hold matches what was last pushed. */
    private function adsMatchThePlatform(Campaign $campaign): bool
    {
        return $campaign->isPublished()
            && ($campaign->published_state['ads_fingerprint'] ?? null)
                === $this->pending->snapshot($campaign)['ads_fingerprint'];
    }

    /** A rename asked for in the same breath as new copy still has to be sent. */
    private function renameAlongside(Campaign $campaign, string $id, string $name): void
    {
        $this->meta->on($campaign->id, $this->actor->describe())
            ->updateEntity($campaign->ad_account_id, $id, 'ad', ['name' => $name]);
    }

    /**
     * Our fields translated into Meta's, for the level being changed.
     *
     * The budget field depends on which kind of budget the object holds, and the
     * amount has to be in minor units - Meta reads 25 as 25 cents. The ad set's
     * own budget_mode wins over the campaign's, because an ad set may hold its
     * own arrangement.
     *
     * @param  array<string,mixed>  $given
     * @return array<string,mixed>
     */
    private function platformFields(Campaign $campaign, ?CampaignAdSet $row, string $type, array $given, ?string $id = null): array
    {
        $fields = [];

        foreach ($given as $field => $value) {
            match ($field) {
                'name' => $fields['name'] = (string) $value,
                'budget' => $fields[$this->budgetField($campaign, $row)] = CurrencyMinorUnits::toMinor((float) $value, $campaign->currency),
                'bid_strategy' => $fields['bid_strategy'] = (string) $value,
                'bid_amount' => $fields['bid_amount'] = CurrencyMinorUnits::toMinor((float) $value, $campaign->currency),
                'starts_at' => $fields['start_time'] = $this->time($value),
                'ends_at' => $fields['end_time'] = $this->time($value),
                'daily_min_spend_target', 'daily_spend_cap', 'lifetime_min_spend_target', 'lifetime_spend_cap' => $fields[$field] = CurrencyMinorUnits::toMinor((float) $value, $campaign->currency),
                'budget_schedule_specs' => $fields['budget_schedule_specs'] = json_encode(
                    $this->scheduleSpecs($value, $campaign->currency),
                    JSON_THROW_ON_ERROR,
                ),
                'roas_average_floor' => $fields['bid_constraints'] = json_encode([
                    'roas_average_floor' => (int) round(((float) $value) * 10000),
                ], JSON_THROW_ON_ERROR),
                'pacing_type' => $fields['pacing_type'] = json_encode(
                    [strtolower(trim((string) (is_array($value) ? ($value[0] ?? '') : $value)))],
                    JSON_THROW_ON_ERROR,
                ),
                'adset_schedule' => $fields['adset_schedule'] = json_encode(
                    $this->dayParts($value),
                    JSON_THROW_ON_ERROR,
                ),
                'targeting' => $fields['targeting'] = json_encode(
                    $this->guard->mergedAudience($campaign, (string) $id, $value),
                    JSON_THROW_ON_ERROR,
                ),
                default => null,
            };
        }

        if (
            $type === 'ad_set'
            && array_key_exists('adset_schedule', $given)
            && $this->dayParts($given['adset_schedule']) !== []
            && ! array_key_exists('pacing_type', $given)
        ) {
            $fields['pacing_type'] = json_encode(['day_parting'], JSON_THROW_ON_ERROR);
        }

        $optimization = array_intersect_key($given, array_flip([
            'conversion_event', 'frequency_control_specs', 'value_rule_set_id', 'value_rules_applied',
        ]));

        if ($type === 'ad_set' && $optimization !== []) {
            $fields = [...$fields, ...$this->guard->optimizationFields($campaign, (string) $id, $optimization)];
        }

        if ($type === 'ad_set' && $id !== null) {
            $fields = $this->withHighestVolume($this->withLiveCostStrategy($campaign, $id, $given, $fields));
        }

        if ($type === 'ad_set' && array_key_exists('budget', $given) && $campaign->usesCampaignBudget()) {
            throw new MetaException(
                'This campaign holds the budget itself, so an ad set has none to change. Change the '
                .'campaign budget instead, or split it across the ad sets first.'
            );
        }

        return $fields;
    }

    /**
     * The ad set fields this request is actually asking to change.
     *
     * @param  array<string, mixed>  $arguments
     * @return array<string, mixed>
     */
    private function givenAdSetFields(array $arguments): array
    {
        $given = array_filter(
            array_intersect_key($arguments, array_flip(self::AD_SET_FIELDS)),
            static fn (mixed $value): bool => $value !== null && $value !== '',
        );

        if (($given['targeting'] ?? null) === []) {
            unset($given['targeting']);
        }

        return $given;
    }

    private function budgetField(Campaign $campaign, ?CampaignAdSet $row): string
    {
        $mode = $row?->budget_mode ?: $campaign->budget_mode;

        return $mode === 'lifetime' ? 'lifetime_budget' : 'daily_budget';
    }

    /**
     * Budget schedule blocks, with ABSOLUTE amounts in minor units.
     *
     * An empty list is kept. Meta reads that as a request to clear the schedule.
     *
     * @return list<array<string, mixed>>
     */
    private function scheduleSpecs(mixed $specs, ?string $currency): array
    {
        if (is_string($specs)) {
            $decoded = json_decode($specs, true);
            $specs = is_array($decoded) ? $decoded : [];
        }

        if (! is_array($specs)) {
            return [];
        }

        return array_values(array_map(function (mixed $spec) use ($currency): array {
            if (! is_array($spec)) {
                return [];
            }

            $type = strtoupper((string) ($spec['budget_value_type'] ?? 'ABSOLUTE'));
            $type = $type === 'MULTIPLIER' ? 'MULTIPLIER' : 'ABSOLUTE';
            $amount = is_numeric($spec['budget_value'] ?? null)
                ? ($type === 'MULTIPLIER'
                    ? (int) $spec['budget_value']
                    : CurrencyMinorUnits::toMinor((float) $spec['budget_value'], $currency))
                : null;

            return array_filter([
                'time_start' => filled($spec['time_start'] ?? null) ? $this->time($spec['time_start']) : null,
                'time_end' => filled($spec['time_end'] ?? null) ? $this->time($spec['time_end']) : null,
                'budget_value' => $amount,
                'budget_value_type' => $amount === null ? null : $type,
            ], static fn (mixed $value): bool => $value !== null);
        }, $specs));
    }

    /**
     * Dayparting blocks. An empty list clears the schedule.
     *
     * @return list<array<string, mixed>>
     */
    private function dayParts(mixed $specs): array
    {
        if (is_string($specs)) {
            $decoded = json_decode($specs, true);
            $specs = is_array($decoded) ? $decoded : [];
        }

        if (! is_array($specs)) {
            return [];
        }

        return array_values(array_map(function (mixed $spec): array {
            if (! is_array($spec)) {
                return [];
            }

            $days = array_values(array_map(static fn (mixed $day): int => (int) $day, (array) ($spec['days'] ?? [])));
            $timezone = strtoupper((string) ($spec['timezone_type'] ?? 'ADVERTISER'));

            return array_filter([
                'days' => $days === [] ? null : $days,
                'start_minute' => is_numeric($spec['start_minute'] ?? null) ? (int) $spec['start_minute'] : null,
                'end_minute' => is_numeric($spec['end_minute'] ?? null) ? (int) $spec['end_minute'] : null,
                'timezone_type' => $timezone === 'USER' ? 'USER' : 'ADVERTISER',
            ], static fn (mixed $value): bool => $value !== null);
        }, $specs));
    }

    /** Meta reads an unqualified time in the ad account's timezone, so it is sent qualified. */
    private function time(mixed $value): string
    {
        return now()->parse((string) $value)->format(\DateTimeInterface::ATOM);
    }

    /**
     * Keep our copy matching the platform, now the platform has confirmed.
     *
     * Only after a successful write, and only then. The campaign's own budget,
     * bid and schedule attributes mirror its first ad set, so editing that one
     * has to move them as well or review_changes starts reporting a difference
     * nobody made - and the snapshot moves with them, for the same reason.
     *
     * @param  array<string,mixed>  $given
     */
    /** A later successful edit replaces the failure still shown on the campaign panel. */
    private function forgetStoredError(Campaign $campaign): void
    {
        if ($campaign->last_error === null) {
            return;
        }

        $campaign->forceFill(['last_error' => null])->save();
    }

    private function recordLocally(Campaign $campaign, ?CampaignAdSet $row, array $given): void
    {
        $stored = $row === null ? [] : array_intersect_key($given, array_flip($row->getFillable()));

        if ($stored !== []) {
            $row->forceFill($stored)->save();
        }

        if ($row === null || (int) $row->id !== (int) $campaign->primaryAdSet?->id) {
            return;
        }

        $campaignStored = array_intersect_key($given, array_flip($campaign->getFillable()));

        if ($campaignStored === []) {
            return;
        }

        $campaign->forceFill($campaignStored)->save();
        $campaign->forceFill(['published_state' => $this->pending->snapshot($campaign->fresh())])->save();
    }

    /**
     * The Google side, which is narrower than Meta's and says why.
     *
     * An ad group holds neither a budget nor a bid strategy on Google - the
     * campaign does - so those are not missing features here, they are
     * questions with no answer at this level, and push_changes is where they
     * belong.
     *
     * An ad is refused outright. GoogleRules::editableAfterPublish already
     * records the reason: "an ad's copy is still replaced rather than edited",
     * which is why ad copy is absent from the list of things a published Google
     * campaign can change. Refusing is better than a partial edit that reports
     * success, and the refusal names the route that does work.
     *
     * @param  array<string,mixed>  $arguments
     */
    private function handleGoogle(Campaign $campaign, string $type, string $id, array $arguments): Stringable|string
    {
        if (! $campaign->isPublished()) {
            return $this->json([
                'ok' => false,
                'error' => 'This campaign has not been published, so there is nothing on Google to change. Change the draft instead.',
            ]);
        }

        if ($type === 'ad') {
            return $this->json([
                'ok' => false,
                'error' => 'A Google ad cannot be edited in place. Google replaces an ad rather than '
                    .'editing it, so its copy, final URL and assets are fixed once it exists.',
                'note' => 'Say that plainly. To change the wording, offer a new ad beside it and then '
                    .'pausing this one with set_entity_status. Do not retry this call.',
            ]);
        }

        $given = array_filter(
            array_intersect_key($arguments, array_flip(self::GOOGLE_AD_GROUP_FIELDS)),
            static fn (mixed $value): bool => $value !== null && $value !== '',
        );

        // Named rather than ignored, for the reason the Meta path gives: a field
        // dropped quietly and then reported as done is an edit the buyer
        // believes happened.
        $refused = array_diff(
            array_keys(array_filter($arguments, static fn (mixed $v): bool => $v !== null && $v !== '')),
            [...self::GOOGLE_AD_GROUP_FIELDS, 'entity_type', 'id'],
        );

        if ($refused !== []) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('%s cannot be changed on a Google ad group.', implode(', ', $refused)),
                'note' => array_intersect($refused, ['budget', 'bid_strategy', 'bid_amount', 'starts_at', 'ends_at'])
                    ? 'On Google the budget, bid strategy and dates belong to the campaign, not the ad '
                        .'group. Use push_changes for those.'
                    : 'Say which field cannot change and do not offer to try it again.',
            ]);
        }

        if ($given === []) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('Nothing to change. On a Google ad group this can change: %s.', implode(', ', self::GOOGLE_AD_GROUP_FIELDS)),
            ]);
        }

        $connection = GoogleAdsConnection::shared();

        if ($connection === null) {
            return $this->json([
                'ok' => false,
                'error' => ucfirst(GoogleAdsConnection::missingReason()).'.',
                'note' => 'Nothing was changed. This needs an administrator.',
            ]);
        }

        // The account the campaign is on, not the configured default. See
        // GoogleAdsConnection::onCustomer - the allow list still gates it.
        $connection = $connection->onCustomer($campaign->ad_account_id);

        $google = app(GoogleAdsService::class);

        try {
            $structure = $google->readCampaignStructure($connection, (string) $campaign->external_campaign_id);

            if (! in_array($id, array_column($structure['ad_groups'], 'id'), true)) {
                return $this->json([
                    'ok' => false,
                    'error' => sprintf('%s is not in this campaign, so nothing was changed.', $id),
                    'note' => 'Call list_campaign_structure for the current ids.',
                ]);
            }

            // The cooldown and the daily cap apply here as they do on Meta and
            // LinkedIn. They did not: this path called neither, so addressing
            // ad groups one at a time was a way around limits the class
            // docblock says it is subject to. Fifty edits a minute on a live
            // campaign all went through.
            $this->guardrails->assertChangeAllowed($campaign->id);

            // Validated before anything is sent, and through the same rules the
            // draft path uses, so the live path cannot accept a set the draft
            // path would have refused. The bound that matters here is the lower
            // one: an edit that removed every keyword would leave a Search ad
            // group that cannot serve, and there is no step to go back to.
            $wanted = isset($given['keywords'])
                ? app(SearchKeywordSelections::class)->validated((array) $given['keywords'])
                : null;

            $fields = [
                ...isset($given['name']) ? ['name' => (string) $given['name']] : [],
                ...isset($given['cpc_bid']) ? ['cpc_bid' => (float) $given['cpc_bid']] : [],
            ];
        } catch (Throwable $e) {
            return $this->json([
                'ok' => false,
                'error' => $e->getMessage(),
                'note' => 'The ad group is unchanged. Say so plainly rather than describing it as partly done.',
            ]);
        }

        // Recorded before the write, as the other two platforms do, so the
        // audit row exists whatever happens next and assertChangeAllowed can
        // count this edit against the ones that follow it.
        $record = CampaignChange::create([
            'campaign_id' => $campaign->id,
            'actor' => $this->actor->describe(),
            'changes' => ['ad_group:'.$id => $given],
            'state' => 'pending',
        ]);

        // Keywords first. They are the change most likely to be refused, by
        // Google or by the rules above, and a refusal after the rename had
        // already gone through would leave the buyer with half an edit and a
        // message saying nothing happened.
        $keywords = null;

        try {
            $keywords = $wanted === null
                ? null
                : $google->replaceAdGroupKeywords($connection, $id, array_map(
                    static fn (array $keyword): array => [
                        'text' => $keyword['text'],
                        'match_type' => $keyword['match_type'],
                        'negative' => $keyword['negative'],
                    ],
                    $wanted,
                ));
        } catch (Throwable $e) {
            $record->update(['state' => 'failed', 'error' => $e->getMessage()]);

            return $this->json([
                'ok' => false,
                'error' => $e->getMessage(),
                'note' => 'The ad group is unchanged. Say so plainly rather than describing it as partly done.',
            ]);
        }

        // Only the fields are left, and by here the keywords may already have
        // been replaced. Reporting "the ad group is unchanged" was wrong in
        // exactly that case, and wrong in a way the buyer cannot see: a Smart
        // Bidding campaign refuses a cpc_bid with
        // OPERATION_NOT_PERMITTED_FOR_CONTEXT, so the keywords were rewritten -
        // their quality-score history gone with them - and the buyer was told
        // nothing had happened and would reasonably try again.
        if ($fields !== []) {
            try {
                $google->updateAdGroup($connection, $id, $fields);
            } catch (Throwable $e) {
                $record->update([
                    'state' => $keywords === null ? 'failed' : 'applied',
                    'error' => $e->getMessage(),
                    ...$keywords === null ? [] : ['applied_at' => now()],
                ]);

                return $this->json(array_filter([
                    'ok' => false,
                    'error' => $e->getMessage(),
                    'keywords' => $keywords,
                    'note' => $keywords === null
                        ? 'The ad group is unchanged. Say so plainly rather than describing it as partly done.'
                        : sprintf(
                            'The keywords were changed and %s was not: %d added, %d removed, %d left '
                                .'alone. Say both halves. The keywords are already live, so do not '
                                .'send them again - only retry the field that was refused.',
                            implode(' and ', array_keys($fields)),
                            $keywords['added'],
                            $keywords['removed'],
                            $keywords['unchanged'],
                        ),
                ], static fn (mixed $value): bool => $value !== null));
            }
        }

        $record->update(['state' => 'applied', 'applied_at' => now()]);

        return $this->json(array_filter([
            'ok' => true,
            'entity_type' => 'ad_group',
            'id' => $id,
            'changed' => array_keys($given),
            'keywords' => $keywords,
            'note' => $keywords === null
                ? 'The ad group was changed on Google. Say which fields changed, in one line.'
                : sprintf(
                    'Keywords on the ad group now: %d added, %d removed, %d left alone. Say those '
                        .'numbers rather than listing every term. The ones left alone keep the '
                        .'history they have built up, which is why they were not rewritten.',
                    $keywords['added'],
                    $keywords['removed'],
                    $keywords['unchanged'],
                ),
        ], static fn (mixed $value): bool => $value !== null));
    }

    /**
     * The ad set the user named, by its Meta id or its current name.
     *
     * A name that matches more than one ad set is listed and nothing is chosen.
     * An id from another campaign is not reused as a guess.
     *
     * @return array{id: string, name: ?string}|array{error: string}
     */
    private function resolveAdSet(Campaign $campaign, string $given): array
    {
        $given = trim($given);

        try {
            $rows = $this->meta->on($campaign->id, $this->actor->describe())
                ->adSets((string) $campaign->external_campaign_id, $campaign->ad_account_id, fresh: true);
        } catch (Throwable $e) {
            return ['error' => 'The ad sets could not be read, so nothing was changed. '.$e->getMessage()];
        }

        foreach ($rows as $row) {
            if ((string) ($row['id'] ?? '') === $given) {
                $name = trim((string) ($row['name'] ?? ''));

                return ['id' => $given, 'name' => $name !== '' ? $name : null];
            }
        }

        $matches = array_values(array_filter(
            $rows,
            static fn (array $row): bool => strcasecmp(trim((string) ($row['name'] ?? '')), $given) === 0,
        ));

        if (count($matches) === 1) {
            return [
                'id' => (string) $matches[0]['id'],
                'name' => trim((string) ($matches[0]['name'] ?? $given)),
            ];
        }

        if ($matches !== []) {
            $listed = implode(', ', array_map(
                static fn (array $row): string => trim((string) ($row['name'] ?? '')).' is '.(string) ($row['id'] ?? ''),
                $matches,
            ));

            return ['error' => 'More than one ad set is named '.$given.'. '.$listed.'. Nothing was changed.'];
        }

        return ['error' => $given.' is not an ad set id or name in this campaign, so nothing was changed.'];
    }

    /**
     * @param  array{id: string, name: ?string}  $resolved
     */
    private function adSetNote(array $resolved): string
    {
        $name = trim((string) ($resolved['name'] ?? ''));

        if ($name !== '' && $name !== $resolved['id']) {
            return sprintf('Ad set %s (%s).', $name, $resolved['id']);
        }

        return 'Ad set '.$resolved['id'].'.';
    }

    private function amountLabel(float $amount, ?string $currency): string
    {
        $text = rtrim(rtrim(number_format($amount, 2, '.', ''), '0'), '.');

        return trim($text.' '.strtoupper(trim((string) $currency)));
    }

    /**
     * Highest volume has no bid amount. The stored cost goal is cleared in the same request.
     *
     * @param  array<string, mixed>  $fields
     * @return array<string, mixed>
     */
    private function withHighestVolume(array $fields): array
    {
        if (($fields['bid_strategy'] ?? null) !== 'LOWEST_COST_WITHOUT_CAP') {
            return $fields;
        }

        $fields['bid_amount'] = '';

        return $fields;
    }

    /**
     * Highest volume after the write. A string is the reason it was not confirmed.
     */
    private function confirmedHighestVolume(Campaign $campaign, string $adSetId): true|string
    {
        try {
            $live = $this->meta->on($campaign->id, $this->actor->describe())
                ->readAdSet($adSetId, $campaign->ad_account_id);
        } catch (Throwable) {
            return 'The bid strategy was sent, but Meta\'s bid strategy could not be read back. Do not tell the user it changed.';
        }

        if (strtoupper(trim((string) ($live['bid_strategy'] ?? ''))) === 'LOWEST_COST_WITHOUT_CAP') {
            return true;
        }

        $still = trim((string) ($live['bid_strategy'] ?? ''));

        return 'Meta left the bid strategy as '.($still !== '' ? $still : 'its previous strategy').'. Highest volume was not applied.';
    }

    /**
     * A cost cap or bid cap has to travel with its amount, or Meta can accept the call and keep the old goal.
     *
     * @param  array<string, mixed>  $given
     * @param  array<string, mixed>  $fields
     * @return array<string, mixed>
     */
    private function withLiveCostStrategy(Campaign $campaign, string $adSetId, array $given, array $fields): array
    {
        if (! array_key_exists('bid_amount', $given) || array_key_exists('bid_strategy', $fields)) {
            return $fields;
        }

        try {
            $live = $this->meta->on($campaign->id, $this->actor->describe())
                ->readAdSet($adSetId, $campaign->ad_account_id);
        } catch (Throwable) {
            return $fields;
        }

        $strategy = strtoupper(trim((string) ($live['bid_strategy'] ?? '')));

        if (in_array($strategy, ['COST_CAP', 'LOWEST_COST_WITH_BID_CAP'], true)) {
            $fields['bid_strategy'] = $strategy;
        }

        return $fields;
    }

    /**
     * The goal Meta has after the write. A string is the reason it was not confirmed.
     */
    private function confirmedBid(Campaign $campaign, string $adSetId, int $sentMinor, float $requested): float|string
    {
        try {
            $live = $this->meta->on($campaign->id, $this->actor->describe())
                ->readAdSet($adSetId, $campaign->ad_account_id);
        } catch (Throwable) {
            return 'The bid was sent, but Meta\'s cost per result goal could not be read back. Do not tell the user it changed.';
        }

        $liveMinor = $live['bid_amount'] ?? null;

        if (is_numeric($liveMinor) && (int) $liveMinor === $sentMinor) {
            return CurrencyMinorUnits::toMajor($sentMinor, $campaign->currency);
        }

        $still = is_numeric($liveMinor)
            ? $this->amountLabel(CurrencyMinorUnits::toMajor((int) $liveMinor, $campaign->currency), $campaign->currency)
            : 'its previous amount';

        return 'Meta left the cost per result goal at '.$still.'. The change to '.$this->amountLabel($requested, $campaign->currency).' was not applied.';
    }

    /**
     * The ids genuinely under this campaign, read fresh.
     *
     * @return list<string>
     */
    private function idsUnder(Campaign $campaign, string $type): array
    {
        $meta = $this->meta->on($campaign->id, $this->actor->describe());
        $external = (string) $campaign->external_campaign_id;

        $rows = $type === 'ad_set'
            ? $meta->adSets($external, $campaign->ad_account_id, fresh: true)
            : $meta->ads($external, $campaign->ad_account_id, fresh: true);

        return array_values(array_filter(array_map(
            static fn (array $r): string => (string) ($r['id'] ?? ''),
            $rows,
        )));
    }
}
