<?php

namespace App\Services;

use App\Campaigns\Manager\Canonical;
use App\Campaigns\Manager\Editing\AdvancedEditFields;
use App\Campaigns\Targeting\GoogleAdAssets;
use App\Models\GoogleAdsCampaign;
use App\Models\GoogleAdsConnection;
use App\Services\Platforms\Support\CallContext;
use App\Services\Platforms\Support\CallLogger;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use RuntimeException;
use Throwable;

class GoogleAdsService
{
    private const array COPY_AD_FIELDS = [
        'id', 'name', 'type', 'final_urls', 'final_mobile_urls', 'tracking_url_template', 'final_url_suffix', 'url_custom_parameters',
        'responsive_search_ad.headlines', 'responsive_search_ad.descriptions', 'responsive_search_ad.path1', 'responsive_search_ad.path2',
        'responsive_display_ad.headlines', 'responsive_display_ad.long_headline', 'responsive_display_ad.descriptions',
        'responsive_display_ad.business_name', 'responsive_display_ad.marketing_images', 'responsive_display_ad.square_marketing_images',
        'responsive_display_ad.logo_images', 'responsive_display_ad.square_logo_images', 'responsive_display_ad.youtube_videos',
        'responsive_display_ad.main_color', 'responsive_display_ad.accent_color', 'responsive_display_ad.allow_flexible_color',
        'responsive_display_ad.call_to_action_text', 'responsive_display_ad.price_prefix', 'responsive_display_ad.promo_text',
        'responsive_display_ad.format_setting', 'responsive_display_ad.control_spec.enable_asset_enhancements',
        'responsive_display_ad.control_spec.enable_autogen_video', 'image_ad.image_url',
    ];

    /** Native criterion blocks that can be reconstructed without translating semantics. */
    private const array COPY_CRITERIA = [
        'KEYWORD' => ['keyword', ['text', 'match_type']],
        'LOCATION' => ['location', ['geo_target_constant']],
        'LANGUAGE' => ['language', ['language_constant']],
        'DEVICE' => ['device', ['type']],
        'AD_SCHEDULE' => ['ad_schedule', ['day_of_week', 'start_hour', 'start_minute', 'end_hour', 'end_minute']],
        'AGE_RANGE' => ['age_range', ['type']],
        'GENDER' => ['gender', ['type']],
        'USER_LIST' => ['user_list', ['user_list']],
        'USER_INTEREST' => ['user_interest', ['user_interest_category']],
        'CUSTOM_AUDIENCE' => ['custom_audience', ['custom_audience']],
        'COMBINED_AUDIENCE' => ['combined_audience', ['combined_audience']],
        'PLACEMENT' => ['placement', ['url']],
        'TOPIC' => ['topic', ['topic_constant']],
        'PARENTAL_STATUS' => ['parental_status', ['type']],
        'INCOME_RANGE' => ['income_range', ['type']],
        'CONTENT_LABEL' => ['content_label', ['type']],
        'IP_BLOCK' => ['ip_block', ['ip_address']],
        'MOBILE_APPLICATION' => ['mobile_application', ['app_id']],
        'MOBILE_APP_CATEGORY' => ['mobile_app_category', ['mobile_app_category_constant']],
        'PROXIMITY' => ['proximity', ['geo_point.latitude_in_micro_degrees', 'geo_point.longitude_in_micro_degrees', 'radius', 'radius_units', 'address.postal_code', 'address.country_code', 'address.province_code', 'address.city_name', 'address.street_address']],
    ];

    // No FALLBACK_REFRESH_TOKEN.
    //
    // A live Google refresh token was committed here as a public constant and
    // used whenever GOOGLE_ADS_REFRESH_TOKEN was unset, which meant any
    // environment missing its configuration silently reached Google as whoever
    // owned that token, and anyone with repository access held a long-lived
    // credential. The token in that constant has to be revoked at Google as
    // well as removed here: deleting it from the source does not un-share it.
    //
    // With it gone, an unconfigured environment fails with the reconnect
    // message below, which is the correct outcome.

    public function __construct(private readonly CallLogger $log) {}

    /**
     * Every call to the Ads API, through the same guardrails Meta's go through.
     *
     * Google was reaching the network directly, which meant three things were
     * true of a Google campaign and not of a Meta one: the account allow list
     * did not apply, the hourly call budget did not count it, and nothing
     * appeared in api_calls, so there was no record that a call had been made
     * at all.
     *
     * The OAuth token exchange deliberately does not come through here. It is
     * not an Ads API call, it does not touch an ad account, and its payload is
     * a refresh token that has no business in an audit row.
     *
     * @param  \Closure(): array<string,mixed>  $call
     * @return array<string,mixed>
     */
    private function audited(string $method, string $endpoint, ?string $customerId, array $request, bool $mutating, \Closure $call, bool $fresh = false, bool $accountChecked = true): array
    {
        return $this->log->record(
            new CallContext(
                transport: 'google_ads',
                method: $method,
                endpoint: $endpoint,
                adAccountId: $customerId,
                request: $request,
                mutating: $mutating,
                accountChecked: $accountChecked,
                platform: 'google',
                memoize: ! $fresh,
            ),
            $call,
        );
    }

    /**
     * The live child accounts under the manager, by id and name.
     *
     * @return list<array{customer_id: string, name: string}>
     */
    public function fetchChildAccounts(GoogleAdsConnection $connection): array
    {
        $managerCustomerId = $connection->manager_customer_id ?: $this->adsConfig($connection)['login_customer_id'] ?? null;
        if (blank($managerCustomerId)) {
            throw new RuntimeException('Select a manager customer before loading child accounts.');
        }

        $managerCustomerId = str_replace('-', '', $managerCustomerId);
        $token = $this->accessToken($connection);
        // The name comes back with the id, which is the point of asking here.
        // childAccountOptions used to read the ids from the connection and then
        // spend one customer read per child to get each name; the manager knows
        // both already, so this is one call instead of one plus N.
        $query = 'SELECT customer_client.client_customer, customer_client.descriptive_name, customer_client.manager, customer_client.status FROM customer_client';
        $headers = $this->requestHeaders($connection);
        $headers['login-customer-id'] = $managerCustomerId;

        // Listing the accounts under a manager is a read of the manager itself,
        // so that is the account the call is attributed to, and it stays in the
        // audit trail as such.
        //
        // The allow list does not apply to this one read. It is the list of
        // accounts ARB may act on, and the manager is not one of them: it is
        // the directory the children are read from. Requiring it meant an
        // administrator had to grant write access to the manager just to let a
        // buyer pick between two children, which is a wider permission than the
        // thing being asked for.
        //
        // Nothing is weakened by this. Every child is filtered through
        // Guardrails::allows() before it is offered - see
        // ListAdAccounts::offerGoogleChildAccounts() - and every read and write
        // of a child account carries its own check. The manager id is not the
        // agent's to choose either: it comes from the connection an
        // administrator made, or from GOOGLE_ADS_LOGIN_CUSTOMER_ID.
        //
        // What it was costing: the refusal was thrown here, caught as a warning
        // in ListAdAccounts, and the flow fell back to "Google runs on one
        // shared account, do not ask the user to choose". So the account
        // question never appeared, however many accounts were permitted, and
        // the reason never reached the buyer or the log they were reading.
        $payload = $this->audited(
            'POST',
            'customers/'.$managerCustomerId.'/googleAds:searchStream',
            $managerCustomerId,
            ['query' => $query],
            mutating: false,
            accountChecked: false,
            call: function () use ($token, $connection, $managerCustomerId, $query): array {
                $response = Http::withToken($token)
                    ->withHeaders([
                        'developer-token' => GoogleAdsConnection::developerToken(),
                        'login-customer-id' => $managerCustomerId,
                        'Content-Type' => 'application/json',
                    ])
                    ->connectTimeout(5)
                    ->timeout(20)
                    ->post('https://googleads.googleapis.com/'.$this->apiVersion($connection).'/customers/'.$managerCustomerId.'/googleAds:searchStream', [
                        'query' => $query,
                    ]);

                if ($response->failed()) {
                    throw new RuntimeException((string) data_get($response->json(), 'error.message', 'Google Ads child accounts could not be loaded.'));
                }

                return $response->json();
            },
        );

        return collect($payload)
            ->flatMap(fn (array $chunk): array => $chunk['results'] ?? [])
            ->map(function (array $result): ?array {
                $client = $result['customerClient'] ?? [];
                if (($client['manager'] ?? true) || ($client['status'] ?? '') !== 'ENABLED') {
                    return null;
                }

                $customerId = str_replace('customers/', '', (string) ($client['clientCustomer'] ?? ''));

                if ($customerId === '') {
                    return null;
                }

                return [
                    'customer_id' => $customerId,
                    'name' => (string) ($client['descriptiveName'] ?? '') ?: 'Google Ads account '.$customerId,
                ];
            })
            ->filter()
            ->unique('customer_id')
            ->values()
            ->all();
    }

    /**
     * The ids alone, for callers that only store the list.
     *
     * @return list<string>
     */
    public function fetchChildAccountIds(GoogleAdsConnection $connection): array
    {
        return array_column($this->fetchChildAccounts($connection), 'customer_id');
    }

    /**
     * The accounts under the manager that a buyer could be offered.
     *
     * Read from the manager when the connection carries no list of its own,
     * which is the case that mattered and the case this could not handle.
     * available_customer_ids is filled by one code path only - the OAuth setup
     * flow in GoogleAdsController - and GoogleAdsConnection::shared() builds
     * its connection from configuration, so on the shared connection the
     * column is always empty and this always returned no options.
     *
     * That is what removed the account step from the Google flow:
     * GoogleRules::defaultAdAccountId records it as "the flow asked which
     * account with nothing on screen, and stopped there", which was an
     * accurate description of the symptom. But the accounts were never
     * missing - a manager customer id is configured, and the children hang off
     * it one call away. The step was deleted where the resolver was at fault.
     *
     * The stored list still wins when there is one, because the OAuth flow
     * persists what that user consented to and narrowing it is deliberate.
     *
     * @return list<array{customer_id: string, name: string}>
     */
    public function childAccountOptions(GoogleAdsConnection $connection): array
    {
        $managerCustomerId = str_replace('-', '', (string) $connection->manager_customer_id);
        $stored = collect($connection->available_customer_ids ?? [])
            ->reject(fn (string $customerId): bool => str_replace('-', '', $customerId) === $managerCustomerId);

        if ($stored->isEmpty()) {
            return collect($this->fetchChildAccounts($connection))
                ->reject(fn (array $account): bool => $account['customer_id'] === $managerCustomerId)
                ->values()
                ->all();
        }

        return $stored
            ->map(function (string $customerId) use ($connection): array {
                $customerId = str_replace('-', '', $customerId);
                $response = $this->search($connection, 'SELECT customer.id, customer.descriptive_name FROM customer WHERE customer.id = '.$customerId, $customerId);
                $customer = data_get($response, '0.results.0.customer', []);

                return [
                    'customer_id' => $customerId,
                    'name' => (string) ($customer['descriptiveName'] ?? 'Google Ads account '.$customerId),
                ];
            })
            ->values()
            ->all();
    }

    /**
     * @param  list<string>  $geoTargets
     * @param  list<string>  $seeds
     * @return list<array{text: string, avg_monthly_searches: int|null, competition: string|null}>
     */
    public function keywordIdeas(GoogleAdsConnection $connection, array $geoTargets, array $seeds, string $language = 'languageConstants/1000'): array
    {
        $customerId = $this->customerId($connection);

        if ($geoTargets === [] || count($geoTargets) > 10
            || array_filter($geoTargets, static fn (string $target): bool => preg_match('/^geoTargetConstants\/[0-9]+$/D', $target) !== 1)
            || $seeds === [] || count($seeds) > 10
            || array_filter($seeds, static fn (string $seed): bool => trim($seed) === '' || mb_strlen($seed) > 80)
            || preg_match('/^languageConstants\/[0-9]+$/D', $language) !== 1) {
            throw new RuntimeException('Keyword research requires 1–10 verified Google geographies, 1–10 short seeds, and a valid language.');
        }

        $body = [
            'language' => $language,
            'geoTargetConstants' => $geoTargets,
            'keywordPlanNetwork' => 'GOOGLE_SEARCH',
            'includeAdultKeywords' => false,
            'pageSize' => 20,
            'keywordSeed' => ['keywords' => $seeds],
        ];
        $token = $this->accessToken($connection);
        $headers = [
            'developer-token' => GoogleAdsConnection::developerToken(),
            'Content-Type' => 'application/json',
        ];
        $loginCustomerId = $connection->manager_customer_id ?: config('services.google_ads.login_customer_id');

        if (filled($loginCustomerId)) {
            $headers['login-customer-id'] = str_replace('-', '', $loginCustomerId);
        }

        $response = $this->audited(
            'POST',
            'customers/'.$customerId.':generateKeywordIdeas',
            $customerId,
            $body,
            mutating: false,
            call: function () use ($token, $headers, $customerId, $body): array {
                $result = Http::withToken($token)->withHeaders($headers)
                    ->connectTimeout(5)->timeout(20)
                    ->post('https://googleads.googleapis.com/'.config('services.google_ads.api_version', 'v25')
                        .'/customers/'.$customerId.':generateKeywordIdeas', $body);

                if ($result->failed()) {
                    throw new RuntimeException((string) data_get($result->json(), 'error.message', 'Google keyword ideas could not be loaded.'));
                }

                return (array) $result->json();
            },
        );

        return collect((array) ($response['results'] ?? []))
            ->take(20)
            ->map(static fn (array $idea): array => [
                'text' => trim((string) ($idea['text'] ?? '')),
                'avg_monthly_searches' => isset($idea['keywordIdeaMetrics']['avgMonthlySearches'])
                    ? (int) $idea['keywordIdeaMetrics']['avgMonthlySearches'] : null,
                'competition' => isset($idea['keywordIdeaMetrics']['competition'])
                    ? (string) $idea['keywordIdeaMetrics']['competition'] : null,
            ])
            ->filter(static fn (array $idea): bool => $idea['text'] !== '')
            ->values()
            ->all();
    }

    /** @return list<array{resource_name: string, name: string, type: string, access_reason: string, eligible_for_search: bool, membership_status: string, access_status: string, size_for_search: int|null}> */
    public function userLists(GoogleAdsConnection $connection, ?string $resourceName = null, ?string $nameSearch = null): array
    {
        $customerId = $this->customerId($connection);

        if ($nameSearch !== null && ! preg_match('/^[\pL\pN ._-]{2,60}$/uD', trim($nameSearch))) {
            throw new RuntimeException('Search for an audience name using 2 to 60 letters or numbers.');
        }

        if ($resourceName !== null
            && ! preg_match('/^customers\/'.$customerId.'\/userLists\/[0-9]+$/D', $resourceName)) {
            throw new RuntimeException('The audience list does not belong to the connected Google Ads customer.');
        }

        $query = 'SELECT user_list.resource_name, user_list.name, user_list.type, '
            .'user_list.access_reason, user_list.eligible_for_search, user_list.membership_status, '
            .'user_list.account_user_list_status, user_list.size_for_search FROM user_list';

        if ($resourceName !== null) {
            $query .= " WHERE user_list.resource_name = '".$resourceName."'";
        } elseif ($nameSearch !== null) {
            $query .= " WHERE user_list.name LIKE '%".trim($nameSearch)."%'";
        }

        $query .= ' LIMIT '.($resourceName === null ? '100' : '1');
        $response = $this->search($connection, $query, fresh: true);

        return collect($response)->flatMap(static fn (array $chunk): array => $chunk['results'] ?? [])
            ->map(static function (array $row): array {
                $list = (array) ($row['userList'] ?? []);

                return [
                    'resource_name' => (string) ($list['resourceName'] ?? ''),
                    'name' => (string) ($list['name'] ?? ''),
                    'type' => (string) ($list['type'] ?? ''),
                    'access_reason' => (string) ($list['accessReason'] ?? ''),
                    'eligible_for_search' => ($list['eligibleForSearch'] ?? false) === true,
                    'membership_status' => (string) ($list['membershipStatus'] ?? ''),
                    'access_status' => (string) ($list['accountUserListStatus'] ?? ''),
                    'size_for_search' => isset($list['sizeForSearch']) ? (int) $list['sizeForSearch'] : null,
                ];
            })
            ->filter(static fn (array $list): bool => $list['resource_name'] !== '' && $list['name'] !== '')
            ->values()
            ->all();
    }

    /**
     * @param  array<string,mixed>  $created  filled in as each object is made,
     *                                        so a failure part way through still
     *                                        knows what exists and can remove it.
     *                                        Without this the ids only appeared
     *                                        on success and a campaign that broke
     *                                        at the ad group left an orphaned
     *                                        campaign and budget on the account.
     */
    public function createPausedCampaign(GoogleAdsConnection $connection, array $data, array &$created = []): array
    {
        $this->customerId($connection);

        if (strtolower((string) ($data['campaign_type'] ?? 'search')) === 'video') {
            $data['campaign_type'] = 'performance_max';
        }

        if (in_array(strtolower((string) ($data['campaign_type'] ?? 'search')), ['search', 'display'], true)) {
            $this->networkSettings($data, []);
        }

        // $created is handed on, not dropped. Both branches build a budget and
        // a campaign before anything that can fail, and neither received it: a
        // Display or Performance Max publish that broke at the ad group, the
        // asset group or the ad left both on the account while $created stayed
        // empty, so rollBack() iterated two blank ids, removed nothing, and the
        // decision recorded that the account was clean. Only the Search branch
        // ever had the guarantee this method's docblock describes.
        // The settled name travels back on the ids rather than in $created,
        // which holds only what exists so a rollback knows what to remove. It
        // is added where the branches return, so a refusal before anything is
        // created still reports an empty $created.
        if (strtolower((string) ($data['campaign_type'] ?? 'search')) === 'display') {
            return $this->withName($this->createPausedDisplayCampaign($connection, $data, $created), $data['name']);
        }

        if (strtolower((string) ($data['campaign_type'] ?? 'search')) === 'performance_max') {
            return $this->withName($this->createPausedPerformanceMaxCampaign($connection, $data, $created), $data['name']);
        }

        if (strtolower((string) ($data['campaign_type'] ?? 'search')) !== 'search') {
            throw new RuntimeException('This Google Ads campaign type is not implemented yet.');
        }

        $explicitKeywordCriteria = array_key_exists('keyword_criteria', $data);
        $keywordCriteria = $data['keyword_criteria'] ?? array_map(
            static fn (string $text): array => ['text' => $text, 'match_type' => 'PHRASE', 'negative' => false],
            array_values(array_filter(array_map('trim', explode(',', (string) ($data['keywords'] ?? ''))))),
        );

        if ($explicitKeywordCriteria && (! is_array($keywordCriteria) || $keywordCriteria === []
            || ! collect($keywordCriteria)->contains(static fn (mixed $keyword): bool => is_array($keyword) && empty($keyword['negative'])))) {
            throw new RuntimeException('At least one included Search keyword is required before creating a Google campaign.');
        }

        if ($explicitKeywordCriteria) {
            foreach ($keywordCriteria as $keyword) {
                if (! is_array($keyword) || ! is_string($keyword['text'] ?? null) || trim($keyword['text']) === ''
                    || ! in_array($keyword['match_type'] ?? null, ['BROAD', 'PHRASE', 'EXACT'], true)
                    || ! is_bool($keyword['negative'] ?? null)) {
                    throw new RuntimeException('Google Search keyword criteria are invalid. Review them before publishing.');
                }
            }
        }

        $userLists = (array) ($data['user_lists'] ?? []);

        foreach ($userLists as $list) {
            if (! is_array($list)
                || ! preg_match('/^customers\/'.$this->customerId($connection).'\/userLists\/[0-9]+$/D', (string) ($list['resource_name'] ?? ''))
                || ! in_array($list['operation'] ?? null, ['include', 'exclude'], true)) {
                throw new RuntimeException('A Google audience list is invalid or belongs to another customer.');
            }
        }

        // Google refuses a campaign whose name an active or paused campaign on
        // the account already has: DUPLICATE_CAMPAIGN_NAME at
        // operations.create.name. The generated name is
        // <page>_<user>-u<id>_<PLATFORM>_<date>, which carries nothing to tell
        // two campaigns apart, so a second campaign for the same landing page
        // by the same person on the same day could not be published at all -
        // and the buyer met a Google error that does not say that renaming it
        // is the fix.
        //
        // Settled here rather than by retrying the refusal: the budget below is
        // created first, so retrying the whole operation would leave an orphan
        // budget on the account every time. And here rather than at the top of
        // createPausedCampaign, so everything that can be refused from the
        // payload alone is still refused without sending anything at all.
        $data['name'] = $this->availableCampaignName($connection, (string) ($data['name'] ?? ''));

        $budgetMicros = (string) round(((float) $data['daily_budget']) * 1000000);
        $budgetResponse = $this->mutate($connection, 'campaignBudgets', [
            'create' => [
                'name' => $data['name'].' Budget',
                'amountMicros' => $budgetMicros,
                'deliveryMethod' => 'STANDARD',
                'explicitlyShared' => false,
            ],
        ]);
        $budgetResource = $this->firstResourceName($budgetResponse, 'campaignBudgetResult');
        if (! is_string($budgetResource)) {
            throw new RuntimeException('Google Ads did not return a campaign budget.');
        }
        $created['budget_id'] = $this->resourceId($budgetResource);

        $response = $this->mutate($connection, 'campaigns', [
            'create' => [
                'name' => $data['name'],
                'status' => 'PAUSED',
                ...$this->trackingTemplateField($data),
                'advertisingChannelType' => 'SEARCH',
                'campaignBudget' => $budgetResource,
                ...$this->biddingSettings(
                    $data['bidding_strategy'] ?? 'max_conversions',
                    isset($data['bid_target']) ? (float) $data['bid_target'] : null,
                    'SEARCH',
                ),
                'geoTargetTypeSetting' => [
                    'positiveGeoTargetType' => $data['positive_geo_target_type'] ?? 'PRESENCE',
                ],
                'containsEuPoliticalAdvertising' => 'DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING',
                ...$this->scheduleSettings($data),
                ...$this->conversionSettings($data),
                'networkSettings' => $this->networkSettings($data, [
                    'targetGoogleSearch' => true,
                    'targetSearchNetwork' => true,
                    'targetContentNetwork' => false,
                    'targetPartnerSearchNetwork' => false,
                ]),
            ],
        ]);

        $campaignResource = $this->firstResourceName($response, 'campaignResult');
        if (! is_string($campaignResource)) {
            throw new RuntimeException('Google Ads did not return a campaign.');
        }
        $created['campaign_id'] = $this->resourceId($campaignResource);

        $this->addTargetingCriteria($connection, $campaignResource, $data);

        // After the create, because the goals do not exist until the
        // campaign does. Google makes one per conversion category on the
        // account and marks them all biddable, so without this a campaign
        // told to optimise for one conversion optimises for every one.
        $this->narrowConversionGoals($connection, $this->resourceId($campaignResource), $data);

        // Sitelinks and callouts, after the campaign exists and before anything
        // that can fail the publish. Not fatal: a campaign without its extras
        // still works, and rolling the whole thing back for them would be worse
        // than publishing without.
        $this->attachCampaignAssets(
            $connection,
            $this->resourceId($campaignResource),
            (array) ($data['sitelinks'] ?? []),
            (array) ($data['callouts'] ?? []),
            is_array($data['structured_snippet'] ?? null) ? $data['structured_snippet'] : null,
        );

        $adGroup = [
            'name' => $data['ad_group_name'],
            'campaign' => $campaignResource,
            // Paused like everything else this method creates. It was the
            // one level left enabled, which nothing served through because
            // the campaign and the ad are both paused, but it made
            // "createPausedCampaign" untrue of a third of what it creates
            // and differed from Meta, where all three levels are paused.
            'status' => 'PAUSED',
            'type' => 'SEARCH_STANDARD',
        ];

        if (collect($userLists)->contains(static fn (array $list): bool => $list['operation'] === 'include')) {
            $adGroup['targetingSetting'] = [
                'targetRestrictions' => [[
                    'targetingDimension' => 'AUDIENCE',
                    'bidOnly' => false,
                ]],
            ];
        }

        // Setting cpcBidMicros on an ad group when the campaign uses Smart Bidding
        // (Target CPA, Maximize Conversions, etc.) is rejected by Google Ads with
        // OPERATION_NOT_PERMITTED_FOR_CONTEXT. Only manual CPC accepts this field.
        if (strtolower((string) ($data['bidding_strategy'] ?? '')) === 'manual_cpc') {
            $adGroup['cpcBidMicros'] = '1000000';
        }

        $adGroupResponse = $this->mutate($connection, 'adGroups', [
            'create' => $adGroup,
        ]);
        $adGroupResource = $this->firstResourceName($adGroupResponse, 'adGroupResult');
        if (! is_string($adGroupResource)) {
            throw new RuntimeException('Google Ads did not return an ad group.');
        }
        $created['ad_group_id'] = $this->resourceId($adGroupResource);

        $keywordOperations = collect($keywordCriteria)
            ->map(fn (array $keyword): array => [
                'create' => [
                    'adGroup' => $adGroupResource,
                    'status' => 'ENABLED',
                    ...($explicitKeywordCriteria ? ['negative' => $keyword['negative']] : []),
                    'keyword' => [
                        'text' => $keyword['text'],
                        'matchType' => $keyword['match_type'],
                    ],
                ],
            ])
            ->values()
            ->all();
        if ($keywordOperations === []) {
            throw new RuntimeException('At least one keyword is required.');
        }
        $this->mutateMany($connection, 'adGroupCriteria', $keywordOperations);

        if ($userLists !== []) {
            $this->mutateMany($connection, 'adGroupCriteria', array_map(
                static fn (array $list): array => [
                    'create' => [
                        'adGroup' => $adGroupResource,
                        'status' => 'ENABLED',
                        'negative' => $list['operation'] === 'exclude',
                        'userList' => ['userList' => $list['resource_name']],
                    ],
                ],
                $userLists,
            ));
        }

        $adResponse = $this->mutate($connection, 'adGroupAds', [
            'create' => [
                'adGroup' => $adGroupResource,
                'status' => 'PAUSED',
                'ad' => [
                    'finalUrls' => [$data['final_url']],
                    'responsiveSearchAd' => [
                        'headlines' => collect($data['headlines'])->map(fn (string $headline): array => ['text' => $headline])->all(),
                        'descriptions' => collect($data['descriptions'])->map(fn (string $description): array => ['text' => $description])->all(),
                        // Optional, and omitted rather than sent empty: Google
                        // refuses a blank display path rather than ignoring it.
                        ...array_filter([
                            'path1' => $data['path1'] ?? null,
                            'path2' => $data['path2'] ?? null,
                        ], static fn (mixed $value): bool => filled($value)),
                    ],
                ],
            ],
        ]);
        $adResource = $this->firstResourceName($adResponse, 'adGroupAdResult');
        if (! is_string($adResource)) {
            throw new RuntimeException('Google Ads did not return an ad.');
        }

        return [
            'budget_id' => $this->resourceId($budgetResource),
            'campaign_id' => $this->resourceId($campaignResource),
            'ad_group_id' => $this->resourceId($adGroupResource),
            'ad_id' => $this->resourceId($adResource),
            // The name the campaign ended up with, which is not always the one
            // asked for: see availableCampaignName().
            'name' => $data['name'],
        ];
    }

    private function createPausedDisplayCampaign(GoogleAdsConnection $connection, array $data, array &$created = []): array
    {
        // Google refuses a campaign whose name an active or paused campaign on
        // the account already has: DUPLICATE_CAMPAIGN_NAME at
        // operations.create.name. The generated name is
        // <page>_<user>-u<id>_<PLATFORM>_<date>, which carries nothing to tell
        // two campaigns apart, so a second campaign for the same landing page
        // by the same person on the same day could not be published at all -
        // and the buyer met a Google error that does not say that renaming it
        // is the fix.
        //
        // Settled here rather than by retrying the refusal: the budget below is
        // created first, so retrying the whole operation would leave an orphan
        // budget on the account every time. And here rather than at the top of
        // createPausedCampaign, so everything that can be refused from the
        // payload alone is still refused without sending anything at all.
        $data['name'] = $this->availableCampaignName($connection, (string) ($data['name'] ?? ''));

        $budgetMicros = (string) round(((float) $data['daily_budget']) * 1000000);
        $budgetResponse = $this->mutate($connection, 'campaignBudgets', [
            'create' => [
                'name' => $data['name'].' Budget',
                'amountMicros' => $budgetMicros,
                'deliveryMethod' => 'STANDARD',
                'explicitlyShared' => false,
            ],
        ]);
        $budgetResource = $this->firstResourceName($budgetResponse, 'campaignBudgetResult');
        if (! is_string($budgetResource)) {
            throw new RuntimeException('Google Ads did not return a Display campaign budget.');
        }
        $created['budget_id'] = $this->resourceId($budgetResource);

        $campaignResponse = $this->mutate($connection, 'campaigns', [
            'create' => [
                'name' => $data['name'],
                'status' => 'PAUSED',
                ...$this->trackingTemplateField($data),
                'advertisingChannelType' => 'DISPLAY',
                'campaignBudget' => $budgetResource,
                ...$this->biddingSettings(
                    $data['bidding_strategy'] ?? 'max_conversions',
                    isset($data['bid_target']) ? (float) $data['bid_target'] : null,
                    'DISPLAY',
                ),
                'geoTargetTypeSetting' => ['positiveGeoTargetType' => 'PRESENCE'],
                'containsEuPoliticalAdvertising' => 'DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING',
                ...$this->scheduleSettings($data),
                ...$this->conversionSettings($data),
                'networkSettings' => $this->networkSettings($data, [
                    'targetGoogleSearch' => false,
                    'targetSearchNetwork' => false,
                    'targetContentNetwork' => true,
                    'targetPartnerSearchNetwork' => false,
                ]),
            ],
        ]);
        $campaignResource = $this->firstResourceName($campaignResponse, 'campaignResult');
        if (! is_string($campaignResource)) {
            throw new RuntimeException('Google Ads did not return a Display campaign.');
        }
        $created['campaign_id'] = $this->resourceId($campaignResource);
        $this->addTargetingCriteria($connection, $campaignResource, $data);

        // After the create, because the goals do not exist until the
        // campaign does. Google makes one per conversion category on the
        // account and marks them all biddable, so without this a campaign
        // told to optimise for one conversion optimises for every one.
        $this->narrowConversionGoals($connection, $this->resourceId($campaignResource), $data);

        // Sitelinks and callouts, after the campaign exists and before anything
        // that can fail the publish. Not fatal: a campaign without its extras
        // still works, and rolling the whole thing back for them would be worse
        // than publishing without.
        $this->attachCampaignAssets(
            $connection,
            $this->resourceId($campaignResource),
            (array) ($data['sitelinks'] ?? []),
            (array) ($data['callouts'] ?? []),
            is_array($data['structured_snippet'] ?? null) ? $data['structured_snippet'] : null,
        );

        $adGroupResponse = $this->mutate($connection, 'adGroups', [
            'create' => [
                'name' => $data['ad_group_name'],
                'campaign' => $campaignResource,
                // Paused, as above.
                'status' => 'PAUSED',
                'type' => 'DISPLAY_STANDARD',
                'cpmBidMicros' => (string) round(((float) ($data['cpm_bid'] ?? 5)) * 1000000),
            ],
        ]);
        $adGroupResource = $this->firstResourceName($adGroupResponse, 'adGroupResult');
        if (! is_string($adGroupResource)) {
            throw new RuntimeException('Google Ads did not return a Display ad group.');
        }

        $imageAsset = static fn (string $resource): array => ['asset' => trim($resource)];
        $adResponse = $this->mutate($connection, 'adGroupAds', [
            'create' => [
                'adGroup' => $adGroupResource,
                'status' => 'PAUSED',
                'ad' => [
                    'finalUrls' => [$data['final_url']],
                    'responsiveDisplayAd' => [
                        'marketingImages' => array_map($imageAsset, $data['marketing_image_assets']),
                        'squareMarketingImages' => array_map($imageAsset, $data['square_marketing_image_assets']),
                        'logoImages' => array_map($imageAsset, $data['logo_image_assets'] ?? []),
                        'headlines' => array_map(fn (string $text): array => ['text' => $text], $data['headlines']),
                        'longHeadline' => ['text' => $data['long_headline']],
                        'descriptions' => array_map(fn (string $text): array => ['text' => $text], $data['descriptions']),
                        'businessName' => $data['business_name'],
                        'callToActionText' => $data['call_to_action_text'] ?? null,
                        'allowFlexibleColor' => true,
                    ],
                ],
            ],
        ]);
        $adResource = $this->firstResourceName($adResponse, 'adGroupAdResult');
        if (! is_string($adResource)) {
            throw new RuntimeException('Google Ads did not return a Display ad.');
        }

        return [
            'budget_id' => $this->resourceId($budgetResource),
            'campaign_id' => $this->resourceId($campaignResource),
            'ad_group_id' => $this->resourceId($adGroupResource),
            'ad_id' => $this->resourceId($adResource),
            // The name the campaign ended up with, which is not always the one
            // asked for: see availableCampaignName().
            'name' => $data['name'],
        ];
    }

    private function createPausedPerformanceMaxCampaign(GoogleAdsConnection $connection, array $data, array &$created = []): array
    {
        // Google refuses a campaign whose name an active or paused campaign on
        // the account already has: DUPLICATE_CAMPAIGN_NAME at
        // operations.create.name. The generated name is
        // <page>_<user>-u<id>_<PLATFORM>_<date>, which carries nothing to tell
        // two campaigns apart, so a second campaign for the same landing page
        // by the same person on the same day could not be published at all -
        // and the buyer met a Google error that does not say that renaming it
        // is the fix.
        //
        // Settled here rather than by retrying the refusal: the budget below is
        // created first, so retrying the whole operation would leave an orphan
        // budget on the account every time. And here rather than at the top of
        // createPausedCampaign, so everything that can be refused from the
        // payload alone is still refused without sending anything at all.
        $data['name'] = $this->availableCampaignName($connection, (string) ($data['name'] ?? ''));

        $budgetMicros = (string) round(((float) $data['daily_budget']) * 1000000);
        $budgetResponse = $this->mutate($connection, 'campaignBudgets', [
            'create' => [
                'name' => $data['name'].' Budget',
                'amountMicros' => $budgetMicros,
                'deliveryMethod' => 'STANDARD',
                'explicitlyShared' => false,
            ],
        ]);
        $budgetResource = $this->firstResourceName($budgetResponse, 'campaignBudgetResult');
        if (! is_string($budgetResource)) {
            throw new RuntimeException('Google Ads did not return a Performance Max budget.');
        }
        $created['budget_id'] = $this->resourceId($budgetResource);

        $campaignResponse = $this->mutate($connection, 'campaigns', [
            'create' => [
                'name' => $data['name'],
                'status' => 'PAUSED',
                ...$this->trackingTemplateField($data),
                'advertisingChannelType' => 'PERFORMANCE_MAX',
                'campaignBudget' => $budgetResource,
                ...$this->biddingSettings(
                    $data['bidding_strategy'] ?? 'max_conversions',
                    isset($data['bid_target']) ? (float) $data['bid_target'] : null,
                    'PERFORMANCE_MAX',
                ),
                // No networkSettings: Performance Max places across every
                // network by definition, which is the whole of what it is.
                ...$this->scheduleSettings($data),
                ...$this->conversionSettings($data),
                'containsEuPoliticalAdvertising' => 'DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING',
            ],
        ]);
        $campaignResource = $this->firstResourceName($campaignResponse, 'campaignResult');
        if (! is_string($campaignResource)) {
            throw new RuntimeException('Google Ads did not return a Performance Max campaign.');
        }
        $created['campaign_id'] = $this->resourceId($campaignResource);
        $this->addTargetingCriteria($connection, $campaignResource, $data);

        // After the create, because the goals do not exist until the
        // campaign does. Google makes one per conversion category on the
        // account and marks them all biddable, so without this a campaign
        // told to optimise for one conversion optimises for every one.
        $this->narrowConversionGoals($connection, $this->resourceId($campaignResource), $data);

        // Sitelinks and callouts, after the campaign exists and before anything
        // that can fail the publish. Not fatal: a campaign without its extras
        // still works, and rolling the whole thing back for them would be worse
        // than publishing without.
        $this->attachCampaignAssets(
            $connection,
            $this->resourceId($campaignResource),
            (array) ($data['sitelinks'] ?? []),
            (array) ($data['callouts'] ?? []),
            is_array($data['structured_snippet'] ?? null) ? $data['structured_snippet'] : null,
        );

        $assetGroupResponse = $this->mutate($connection, 'assetGroups', [
            'create' => [
                'campaign' => $campaignResource,
                'name' => $data['asset_group_name'],
                // Paused, as above. A Performance Max campaign has no ad to
                // pause separately, so the asset group is the only level below
                // the campaign there is.
                'status' => 'PAUSED',
                'finalUrls' => [$data['final_url']],
            ],
        ]);
        $assetGroupResource = $this->firstResourceName($assetGroupResponse, 'assetGroupResult');
        if (! is_string($assetGroupResource)) {
            throw new RuntimeException('Google Ads did not return a Performance Max asset group.');
        }

        $links = [];

        // Each line is created as an asset first. The publisher hands over the
        // copy as plain strings, the way a responsive search ad takes it, and
        // an asset group links resource names instead - so these used to put a
        // headline where Google expected customers/<id>/assets/<id>.
        $text = fn (string $line): string => $this->createTextAsset($connection, $line);

        foreach ($data['headlines'] as $line) {
            $links[] = ['assetGroup' => $assetGroupResource, 'asset' => $text($line), 'fieldType' => 'HEADLINE'];
        }
        foreach ($data['long_headlines'] as $line) {
            $links[] = ['assetGroup' => $assetGroupResource, 'asset' => $text($line), 'fieldType' => 'LONG_HEADLINE'];
        }
        foreach ($data['descriptions'] as $line) {
            $links[] = ['assetGroup' => $assetGroupResource, 'asset' => $text($line), 'fieldType' => 'DESCRIPTION'];
        }

        // Required by Google, and absent until now. The Display branch sends a
        // business name as a field on the ad; an asset group has no such field,
        // it has to be linked like any other asset, so a Performance Max group
        // was always built without one.
        if (filled($data['business_name'] ?? null)) {
            $links[] = ['assetGroup' => $assetGroupResource, 'asset' => $text((string) $data['business_name']), 'fieldType' => 'BUSINESS_NAME'];
        }
        foreach ($data['marketing_image_assets'] as $asset) {
            $links[] = ['assetGroup' => $assetGroupResource, 'asset' => $asset, 'fieldType' => 'MARKETING_IMAGE'];
        }
        foreach ($data['square_marketing_image_assets'] as $asset) {
            $links[] = ['assetGroup' => $assetGroupResource, 'asset' => $asset, 'fieldType' => 'SQUARE_MARKETING_IMAGE'];
        }
        // Performance Max is the only type with a portrait slot; a responsive
        // display ad has no field for one.
        foreach (($data['portrait_marketing_image_assets'] ?? []) as $asset) {
            $links[] = ['assetGroup' => $assetGroupResource, 'asset' => $asset, 'fieldType' => 'PORTRAIT_MARKETING_IMAGE'];
        }
        foreach (($data['logo_image_assets'] ?? []) as $asset) {
            $links[] = ['assetGroup' => $assetGroupResource, 'asset' => $asset, 'fieldType' => 'LOGO'];
        }
        foreach (($data['youtube_video_assets'] ?? []) as $asset) {
            $links[] = ['assetGroup' => $assetGroupResource, 'asset' => $asset, 'fieldType' => 'YOUTUBE_VIDEO'];
        }
        $this->mutateMany($connection, 'assetGroupAssets', array_map(fn (array $link): array => ['create' => $link], $links));

        return [
            'budget_id' => $this->resourceId($budgetResource),
            'campaign_id' => $this->resourceId($campaignResource),
            'asset_group_id' => $this->resourceId($assetGroupResource),
            'ad_group_id' => null,
            'ad_id' => null,
        ];
    }

    public function createYouTubeVideoAsset(GoogleAdsConnection $connection, string $videoId, ?string $name = null): string
    {
        $response = $this->mutate($connection, 'assets', [
            'create' => [
                'name' => $name ?: 'YouTube video '.$videoId,
                'type' => 'YOUTUBE_VIDEO',
                'youtubeVideoAsset' => [
                    'youtubeVideoId' => $videoId,
                ],
            ],
        ]);

        $resource = $this->firstResourceName($response, 'assetResult');
        if (! is_string($resource)) {
            throw new RuntimeException('Google Ads did not return a YouTube video asset.');
        }

        return $resource;
    }

    /**
     * A line of copy as a Google asset, which is what an asset group links.
     *
     * A Performance Max asset group does not carry text the way a responsive
     * search ad does. It links assets, each identified by a resource name, so
     * every headline, description and the business name has to exist as an
     * asset before the group can point at it.
     *
     * Nothing created them. The asset-group builder was written expecting
     * resource names - it passes each entry straight into the link's "asset"
     * field - while the publisher hands it the raw strings it reads off the ad
     * rows, so Google was being sent a headline where it expected
     * customers/<id>/assets/<id>. The method that would have made them,
     * createTextAsset, is one of the several that app/Mcp/Tools/GoogleAds calls
     * and that have never existed on this class.
     *
     * Text assets are deduplicated by Google per account, so sending the same
     * line twice returns the same asset rather than making a second one.
     *
     * @return string the asset resource name
     */
    public function createTextAsset(GoogleAdsConnection $connection, string $text): string
    {
        $text = trim($text);

        if ($text === '') {
            throw new RuntimeException('A Google text asset cannot be empty.');
        }

        $response = $this->mutate($connection, 'assets', [
            'create' => [
                'type' => 'TEXT',
                'textAsset' => ['text' => $text],
            ],
        ]);

        $resource = $this->firstResourceName($response, 'assetResult');

        if (! is_string($resource)) {
            throw new RuntimeException('Google Ads did not return a text asset.');
        }

        return $resource;
    }

    /**
     * Sitelinks and callouts on the campaign, which had none.
     *
     * Both are campaign level assets in Google's model: the asset itself is
     * made once on the account, then a CampaignAsset row points the campaign at
     * it with a fieldType saying what it is for. Nothing else in this class
     * writes campaignAssets, so the link half is as new as the assets.
     *
     * Deliberately not fatal. A campaign that published and then could not take
     * its sitelinks is a working campaign missing an extra, and throwing here
     * would roll back the whole publish for it. The failure is returned so the
     * caller can say so rather than swallowed.
     *
     * @param  list<array{text: string, final_url: string}>  $sitelinks
     * @param  list<string>  $callouts
     * @param  array{header: string, values: list<string>}|null  $snippet
     * @return array{attached: int, failed: ?string}
     */
    public function attachCampaignAssets(
        GoogleAdsConnection $connection,
        string $campaignId,
        array $sitelinks,
        array $callouts,
        ?array $snippet = null,
    ): array {
        if ($sitelinks === [] && $callouts === [] && $snippet === null) {
            return ['attached' => 0, 'failed' => null];
        }

        $customerId = $this->customerId($connection);
        $campaign = sprintf('customers/%s/campaigns/%s', $customerId, $campaignId);
        $links = [];

        try {
            foreach ($sitelinks as $sitelink) {
                $text = trim((string) ($sitelink['text'] ?? ''));
                $url = trim((string) ($sitelink['final_url'] ?? ''));

                if ($text === '' || $url === '') {
                    continue;
                }

                $response = $this->mutate($connection, 'assets', [
                    'create' => [
                        'type' => 'SITELINK',
                        'finalUrls' => [$url],
                        'sitelinkAsset' => ['linkText' => $text],
                    ],
                ]);

                if (is_string($resource = $this->firstResourceName($response, 'assetResult'))) {
                    $links[] = ['create' => [
                        'campaign' => $campaign,
                        'asset' => $resource,
                        'fieldType' => 'SITELINK',
                    ]];
                }
            }

            foreach ($callouts as $callout) {
                $text = trim((string) $callout);

                if ($text === '') {
                    continue;
                }

                $response = $this->mutate($connection, 'assets', [
                    'create' => [
                        'type' => 'CALLOUT',
                        'calloutAsset' => ['calloutText' => $text],
                    ],
                ]);

                if (is_string($resource = $this->firstResourceName($response, 'assetResult'))) {
                    $links[] = ['create' => [
                        'campaign' => $campaign,
                        'asset' => $resource,
                        'fieldType' => 'CALLOUT',
                    ]];
                }
            }

            // One snippet, because a campaign showing two lists under two
            // headers reads as a site map rather than an ad.
            $values = array_values(array_filter(array_map('strval', (array) ($snippet['values'] ?? []))));
            $header = trim((string) ($snippet['header'] ?? ''));

            // Checked here as well as in GoogleAdAssets, because this method is
            // public and a second caller would not know Google's header list is
            // fixed. Google would refuse it anyway; this refuses it without
            // spending a call and without losing the sitelinks in the same
            // batch to one bad snippet.
            if ($header !== '' && count($values) >= 3 && GoogleAdAssets::acceptsHeader($header)) {
                $response = $this->mutate($connection, 'assets', [
                    'create' => [
                        'type' => 'STRUCTURED_SNIPPET',
                        'structuredSnippetAsset' => ['header' => $header, 'values' => $values],
                    ],
                ]);

                if (is_string($resource = $this->firstResourceName($response, 'assetResult'))) {
                    $links[] = ['create' => [
                        'campaign' => $campaign,
                        'asset' => $resource,
                        'fieldType' => 'STRUCTURED_SNIPPET',
                    ]];
                }
            }

            if ($links !== []) {
                $this->mutateMany($connection, 'campaignAssets', $links);
            }
        } catch (Throwable $e) {
            // Logged here rather than only returned. This is deliberately not
            // fatal, which means every caller is free to ignore the result -
            // and all three of them did, so a campaign that silently got no
            // sitelinks looked identical to one whose page had none to give.
            Log::warning('Google campaign assets were not attached', [
                'campaign' => $campaignId,
                'sitelinks' => count($sitelinks),
                'callouts' => count($callouts),
                'snippet' => $snippet !== null,
                'error' => $e->getMessage(),
            ]);

            return ['attached' => 0, 'failed' => $e->getMessage()];
        }

        return ['attached' => count($links), 'failed' => null];
    }

    public function createImageAsset(GoogleAdsConnection $connection, string $contents, string $name): string
    {
        $response = $this->mutate($connection, 'assets', [
            'create' => [
                'name' => $name,
                'type' => 'IMAGE',
                'imageAsset' => [
                    'data' => base64_encode($contents),
                ],
            ],
        ]);

        $resource = $this->firstResourceName($response, 'assetResult');
        if (! is_string($resource)) {
            throw new RuntimeException('Google Ads did not return an image asset.');
        }

        return $resource;
    }

    /**
     * The campaign's bidding, including the number it aims at.
     *
     * Accepts both the short names the Google chat used and the API's own
     * names, which is what the unified flow stores on the campaign because
     * that is the vocabulary GoogleRules offers the user.
     *
     * The target matters. This used to fall through to maximizeConversions for
     * anything it did not recognise, so a campaign set to TARGET_CPA with a
     * target the user chose was created bidding for volume at any price, and
     * nothing anywhere said the number had been dropped.
     *
     * @param  float|null  $target  cost per action, or the ROAS multiple
     * @return array<string,mixed>
     */
    /**
     * Change a published campaign, one field set at a time.
     *
     * Separate from updateCampaign() above, which belongs to the older Google
     * chat and takes its GoogleAdsCampaign model. This one is given the ids the
     * publisher recorded and the values already shaped for Google, so the
     * mapping from our fields stays in GooglePublisher next to the mapping that
     * created them.
     *
     * updateMask is not optional and is not a formality: Google clears any
     * field named in the mask and absent from the payload, so a mask wider than
     * the change would blank whatever else it covers.
     *
     * @param  array<string,mixed>  $fields  Google field names to values
     */
    public function updateLiveCampaign(GoogleAdsConnection $connection, string $campaignId, array $fields): void
    {
        if ($fields === []) {
            return;
        }

        $this->mutate($connection, 'campaigns', [
            'update' => [
                'resourceName' => 'customers/'.$this->customerId($connection).'/campaigns/'.$campaignId,
                ...$fields,
            ],
            'updateMask' => $this->updateMask($fields),
        ]);
    }

    /**
     * The mask Google accepts, which names leaves rather than blocks.
     *
     * A mask naming a field that has subfields is refused outright with
     * FIELD_HAS_SUBFIELDS, so "maximizeConversions" and "networkSettings" were
     * both rejected and no edit to a live campaign's bidding or networks ever
     * reached Google. It failed the same way before the bidding fix, with
     * "targetCpa" in the mask, so this is not new - it is just the first time
     * anything got far enough to see it.
     *
     * One level is enough: every block sent here is a flat message.
     *
     * @param  array<string,mixed>  $fields
     */
    private function updateMask(array $fields): string
    {
        $paths = [];

        foreach ($fields as $name => $value) {
            if ($name === 'frequencyCaps') {
                $paths[] = $name;

                continue;
            }

            $subfields = is_object($value) ? get_object_vars($value) : (is_array($value) ? $value : null);

            if ($subfields === null) {
                $paths[] = (string) $name;

                continue;
            }

            // An empty block is "this strategy, with no target", and it still
            // has to be masked at a leaf: naming the block is refused, and the
            // leaf is what selects the strategy. See EMPTY_BLOCK_LEAF.
            //
            // A block with no leaf listed there falls back to its own name, so
            // the refusal is Google's and legible rather than a mask this
            // guessed at.
            if ($subfields === []) {
                $leaf = self::EMPTY_BLOCK_LEAF[$name] ?? null;
                $paths[] = $leaf === null ? (string) $name : $name.'.'.$leaf;

                continue;
            }

            foreach (array_keys($subfields) as $subfield) {
                $paths[] = $name.'.'.$subfield;
            }
        }

        return implode(',', $paths);
    }

    /**
     * One leaf per bidding block, for switching to a strategy with no target.
     *
     * Google picks the strategy from whichever of these one-of blocks the
     * update names, and the mask has to name a field inside it: the block alone
     * is refused with FIELD_HAS_SUBFIELDS. So an empty block plus a leaf in the
     * mask says both things at once - use this strategy, and leave its target
     * unset - and the value being absent is what clears the old target.
     *
     * Each of these was run for real against a paused campaign on account
     * 346-085-5874 and the strategy read back from Google afterwards:
     *
     *   maximizeConversions{}     + maximize_conversions.target_cpa_micros
     *                               -> MAXIMIZE_CONVERSIONS, no target CPA
     *   maximizeConversionValue{} + maximize_conversion_value.target_roas
     *                               -> MAXIMIZE_CONVERSION_VALUE, no target ROAS
     *   targetSpend{}             + target_spend.cpc_bid_ceiling_micros
     *                               -> TARGET_SPEND, no bid ceiling
     *
     * Masking bidding_strategy_type instead looks like it works and does not:
     * Google accepts the update, reports success and leaves the strategy
     * exactly as it was. It is output only, and validateOnly says nothing about
     * that, which is why these were checked by reading the campaign back rather
     * than by validating the call.
     *
     * Clearing the leaf alongside the switch is wanted in every case here. A
     * target CPA belongs to the strategy that had one, and a bid ceiling left
     * over from maximise clicks would silently cap a strategy that never asked
     * for it.
     */
    private const EMPTY_BLOCK_LEAF = [
        'maximizeConversions' => 'targetCpaMicros',
        'maximizeConversionValue' => 'targetRoas',
        'targetSpend' => 'cpcBidCeilingMicros',
        'manualCpc' => 'enhancedCpcEnabled',
    ];

    /**
     * Set the status of a campaign, its ad group and its ad together.
     *
     * Google calls live ENABLED rather than ACTIVE, and every level has its own:
     * an ENABLED campaign over a PAUSED ad group serves nothing and reports it as
     * a campaign with no impressions, which is indistinguishable from one that is
     * simply not winning any auctions.
     *
     * Three mutates rather than one, because they are three resource types.
     *
     * @param  array<string,mixed>  $ids  as recorded by createPausedCampaign
     */
    public function setLiveStatus(GoogleAdsConnection $connection, array $ids, string $status): void
    {
        $customerId = $this->customerId($connection);

        $adGroupId = $ids['ad_group_id'] ?? null;
        $adId = $ids['ad_id'] ?? null;

        // The collection is the path, so the two cannot drift apart.
        //
        // They had. The ad level posted to ads:mutate while naming an
        // adGroupAds resource, and built that name as adGroupAds/<adId>. Both
        // halves were wrong. An AdGroupAd is keyed by both ids - confirmed
        // against the live account, which returns
        // customers/3460855874/adGroupAds/191986261905~795772820090 - and
        // status is a field of AdGroupAd rather than Ad, so ads:mutate could
        // not have set it under any resource name.
        //
        // Mutations throw, and this level runs first, so every call that
        // carried an ad id threw here before the ad group or the campaign was
        // touched. activate() carries one on every Google campaign.
        // Performance Max keeps its creative in an asset group and has no ad
        // group to find, so a PMax campaign recorded only a campaign id and an
        // asset_group_id. Nothing here wrote asset groups, and the asset group
        // is created PAUSED, so activate() enabled the campaign and left the
        // only thing that can serve switched off. isLive() then read the
        // campaign as ENABLED and reported it live - a campaign serving
        // nothing, indistinguishable from one losing every auction, which is
        // the exact failure this method's docblock exists to prevent.
        $levels = [
            'adGroupAds' => filled($adGroupId) && filled($adId) ? $adGroupId.'~'.$adId : null,
            'adGroups' => $adGroupId,
            'assetGroups' => $ids['asset_group_id'] ?? null,
            'campaigns' => $ids['campaign_id'] ?? null,
        ];

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

            $this->mutateStatus($connection, $customerId, $collection, (string) $id, $status);
        }
    }

    /**
     * One ad group or one ad, without touching anything above it.
     *
     * setLiveStatus writes every level it is handed, which is what activate and
     * pause want and the opposite of what pausing a single ad wants: an ad's
     * resource name needs its ad group id, and handing that to setLiveStatus
     * would pause the ad group too - the whole campaign's delivery instead of
     * one ad.
     *
     * @param  'ad_group'|'ad'|'asset_group'  $level
     */
    public function setChildStatus(
        GoogleAdsConnection $connection,
        string $level,
        string $id,
        ?string $adGroupId,
        string $status,
    ): void {
        if ($level === 'ad' && blank($adGroupId)) {
            throw new RuntimeException('A Google ad cannot be addressed without its ad group id.');
        }

        $collection = match ($level) {
            'ad' => 'adGroupAds',
            'asset_group' => 'assetGroups',
            default => 'adGroups',
        };

        $this->mutateStatus(
            $connection,
            $this->customerId($connection),
            $collection,
            $level === 'ad' ? $adGroupId.'~'.$id : $id,
            $status,
        );
    }

    /** The one place a status resource name is built, so it is built one way. */
    private function mutateStatus(
        GoogleAdsConnection $connection,
        string $customerId,
        string $collection,
        string $resourceId,
        string $status,
    ): void {
        $this->mutate($connection, $collection, [
            'update' => [
                'resourceName' => sprintf('customers/%s/%s/%s', $customerId, $collection, $resourceId),
                'status' => $status,
            ],
            'updateMask' => 'status',
        ]);
    }

    /** The money lives on its own resource, so it is its own call. */
    public function updateLiveBudget(GoogleAdsConnection $connection, string $budgetId, float $daily): void
    {
        $this->mutate($connection, 'campaignBudgets', [
            'update' => [
                'resourceName' => 'customers/'.$this->customerId($connection).'/campaignBudgets/'.$budgetId,
                'amountMicros' => (string) $this->micros($daily),
            ],
            'updateMask' => 'amountMicros',
        ]);
    }

    /**
     * The network block for a set of chosen networks, for callers outside.
     *
     * @param  list<string>  $networks
     * @param  array<string,bool>  $default
     * @return array<string,bool>
     */
    public function networksFor(array $networks, array $default): array
    {
        return $this->networkSettings(['networks' => $networks], $default);
    }

    /**
     * The bidding block for a strategy, for callers outside this class.
     *
     * Exposed so an update sends the same shape as the create did rather than a
     * second reading of the same rules.
     *
     * @return array<string,mixed>
     */
    public function biddingFor(string $strategy, ?float $target = null, ?string $channel = null): array
    {
        return $this->biddingSettings($strategy, $target, $channel);
    }

    /**
     * The name as given, or the first free variation of it.
     *
     * Google's uniqueness is per account and counts active and paused
     * campaigns, not removed ones, so the question is only answerable by
     * asking it. One read, and only the names are fetched.
     *
     * The suffix is " 2", " 3" and so on rather than a timestamp or a random
     * string: it is what a person would write, it sorts beside the original,
     * and it says plainly that this is the second campaign for that page today
     * rather than looking like an id. Capped so a pathological account cannot
     * spin here; past the cap the name goes out as asked and Google's refusal
     * stands, which is at least the behaviour that existed before.
     *
     * A name is never shortened to fit the suffix. Google allows far longer
     * names than anything generated here, and quietly truncating somebody's
     * campaign name to make room is a worse surprise than a long name.
     */
    private function availableCampaignName(GoogleAdsConnection $connection, string $name): string
    {
        $name = trim($name);

        if ($name === '') {
            return $name;
        }

        try {
            $rows = $this->searchRows($connection, <<<'GAQL'
SELECT campaign.name FROM campaign WHERE campaign.status != 'REMOVED'
GAQL);
        } catch (Throwable $e) {
            // The account could not be read. Send the name as asked rather
            // than inventing a variation of it: a duplicate is refused loudly
            // by Google, and a wrong name is not refused at all.
            Log::warning('Could not read Google campaign names; sending the name unchanged', [
                'name' => $name,
                'error' => $e->getMessage(),
            ]);

            return $name;
        }

        $taken = [];

        foreach ($rows as $row) {
            $existing = trim((string) data_get($row, 'campaign.name', ''));

            if ($existing !== '') {
                $taken[mb_strtolower($existing)] = true;
            }
        }

        if (! isset($taken[mb_strtolower($name)])) {
            return $name;
        }

        for ($suffix = 2; $suffix <= self::MOST_NAME_ATTEMPTS; $suffix++) {
            // " #2" rather than " 2", which is the convention the buyers
            // already use by hand on these accounts, and which cannot be read
            // as part of the name the way a bare trailing number can.
            $candidate = $name.' #'.$suffix;

            if (! isset($taken[mb_strtolower($candidate)])) {
                return $candidate;
            }
        }

        return $name;
    }

    /** Past this the name goes out as asked and Google decides. */
    private const MOST_NAME_ATTEMPTS = 50;

    /**
     * The created ids, plus the name the campaign ended up with.
     *
     * @param  array<string,mixed>  $ids
     * @return array<string,mixed>
     */
    private function withName(array $ids, string $name): array
    {
        return [...$ids, 'name' => $name];
    }

    /**
     * The advertising channel a campaign type creates on.
     *
     * Public because bidding depends on it and the update path has the type
     * rather than the channel. Kept here beside the create paths that hold the
     * channel literally, so the two cannot drift.
     */
    public function channelFor(?string $campaignType): string
    {
        return match (strtolower(trim((string) $campaignType))) {
            'display' => 'DISPLAY',
            // Video is published as Performance Max; see createCampaign().
            'performance_max', 'video' => 'PERFORMANCE_MAX',
            default => 'SEARCH',
        };
    }

    /**
     * Where the bidding target lives, which is not the same field everywhere.
     *
     * Google retired the standalone TargetCpa and TargetRoas strategies for
     * Search and Performance Max: the target moved inside MaximizeConversions
     * and MaximizeConversionValue, and sending the old field is refused with
     * OPERATION_NOT_PERMITTED_FOR_CONTEXT at operations.create.target_cpa. That
     * is the refusal a buyer met publishing a Search campaign with a $0.71
     * target CPA, after answering all twelve questions.
     *
     * Display did not move. It still takes campaign.target_cpa and refuses
     * maximize_conversions.target_cpa_micros, so the shape has to follow the
     * channel rather than pick one and hope. Verified against account
     * 346-085-5874 with validateOnly on every channel and both shapes.
     *
     * A ROAS target is the exception: maximize_conversion_value.target_roas is
     * accepted on Search and Display alike, so it needs no branch.
     */
    private function biddingSettings(string $strategy, ?float $target = null, ?string $channel = null): array
    {
        // A target of zero is not a target, so it is not sent as one. Google
        // reads a zero target_cpa_micros as "unset" rather than as a $0.00
        // target - checked by sending one and reading the campaign back - so
        // this is not the difference between bidding and not bidding. It is
        // still omitted: the strategy without an amount is the strategy without
        // an amount, and a zero in the payload only invites the reader to
        // wonder which it meant.
        $micros = $target !== null && $target > 0 ? (string) $this->micros($target) : null;

        return match (strtolower($strategy)) {
            'target_cpa', 'target_cpa_bidding' => match (true) {
                $micros === null => ['maximizeConversions' => (object) []],
                strtoupper(trim((string) $channel)) === 'DISPLAY' => ['targetCpa' => ['targetCpaMicros' => $micros]],
                default => ['maximizeConversions' => ['targetCpaMicros' => $micros]],
            },
            'target_roas' => [
                // A ROAS target is a multiple, not money: 4.0 means four times
                // the spend back. Sent as a plain double rather than micros.
                'maximizeConversionValue' => ['targetRoas' => (float) ($target ?? 1.0)],
            ],
            'max_conversion_value', 'maximize_conversion_value' => ['maximizeConversionValue' => (object) []],
            'max_clicks', 'maximize_clicks' => ['targetSpend' => (object) []],
            'manual_cpc' => ['manualCpc' => ['enhancedCpcEnabled' => false]],
            default => ['maximizeConversions' => (object) []],
        };
    }

    /**
     * Which networks the campaign is allowed to run on.
     *
     * These were hardcoded per campaign type, so the networks a buyer picked
     * were collected, shown back to them in the panel, and then thrown away: a
     * campaign told to run on Display only was created on Search only.
     *
     * The defaults stand when nothing was chosen, which is what every campaign
     * built before the question existed relies on.
     *
     * @param  array<string,mixed>  $data
     * @param  array<string,bool>  $default
     * @return array<string,bool>
     */
    private function networkSettings(array $data, array $default): array
    {
        $chosen = $this->targetingValues($data['networks'] ?? null);

        if ($chosen === []) {
            return $default;
        }

        $unsupported = array_diff($chosen, ['search', 'search_partners', 'display']);

        if ($unsupported !== []) {
            throw new RuntimeException('Google network selection cannot be sent: '.implode(', ', $unsupported).'. Use a separate campaign for YouTube.');
        }

        return [
            'targetGoogleSearch' => in_array('search', $chosen, true),
            'targetSearchNetwork' => in_array('search_partners', $chosen, true),
            'targetContentNetwork' => in_array('display', $chosen, true),
            'targetPartnerSearchNetwork' => false,
        ];
    }

    /**
     * When the campaign runs, if anybody said.
     *
     * Dates were never sent at all, so a campaign given an end date ran until
     * somebody noticed. Google v25 accepts date and time in the account timezone.
     *
     * @param  array<string,mixed>  $data
     * @return array<string,string>
     */
    private function scheduleSettings(array $data): array
    {
        return array_filter([
            'startDateTime' => filled($data['starts_at'] ?? null)
                ? date('Y-m-d 00:00:00', strtotime((string) $data['starts_at'])) : null,
            'endDateTime' => filled($data['ends_at'] ?? null)
                ? date('Y-m-d 23:59:59', strtotime((string) $data['ends_at'])) : null,
        ], fn (?string $value): bool => $value !== null);
    }

    /**
     * What the campaign counts as a conversion.
     *
     * Nothing set this. The flow asks for a conversion action, the publish gate
     * refuses a sales or leads campaign without one, and then it went nowhere:
     * the campaign bid toward conversions while telling Google nothing about
     * which conversions to count.
     *
     * selectiveOptimization is the campaign level field for it, which is what
     * makes the answer actually reach the thing being optimised.
     *
     * @param  array<string,mixed>  $data
     * @return array<string,mixed>
     */
    /**
     * Nothing on the campaign itself, which is the point.
     *
     * This once sent selectiveOptimization naming the chosen conversion action,
     * on Search, Display and Performance Max alike. Google refuses it outright
     * on Search: publishing campaign 54 on 23 Sep failed the campaign create
     * with OPERATION_NOT_PERMITTED_FOR_CONTEXT and named no field. Selective
     * optimization belongs to App campaigns.
     *
     * A Search campaign says which conversions it counts through its conversion
     * goals, which are separate resources and cannot be set until the campaign
     * exists. See narrowConversionGoals(), called straight after the create.
     *
     * @param  array<string,mixed>  $data
     * @return array<string,mixed>
     */
    private function conversionSettings(array $data): array
    {
        return [];
    }

    /**
     * Count only the conversion the buyer chose.
     *
     * Google gives a new campaign one conversion goal per category that has a
     * conversion action on the account, every one of them biddable, so a
     * campaign told to optimise for "Book Demo" also optimises for "Purchase"
     * and every other category configured. That is the account's setting
     * leaking into a campaign that was asked a question about itself.
     *
     * The goals cannot be created, only flipped: Google makes them with the
     * campaign and the resource name is deterministic, {campaignId}~{CATEGORY}~
     * {ORIGIN}. Confirmed against the live account: the update is accepted and
     * the goal reads back with biddable absent, which is how Google says false.
     *
     * Both directions, because a campaign does not start with everything on.
     * It inherits the account's customer_conversion_goal settings, so a
     * category the account has switched off is off on the campaign too. This
     * only ever switched categories off, so a buyer who picked such a category
     * got a campaign that silently did not count it: reported as "selected 4,
     * out of that only 2 were seen" on campaign 24377550714, where
     * SUBSCRIBE_PAID is off at the account level and was also the campaign's
     * primary. The two that stuck were the two the account already had on.
     *
     * Everything is left alone when the chosen action's category cannot be
     * found. A campaign counting more conversions than asked still spends
     * sensibly; one counting none at all cannot optimise toward anything.
     *
     * @param  array<string,mixed>  $data
     */
    private function narrowConversionGoals(GoogleAdsConnection $connection, string $campaignId, array $data): void
    {
        // Every action the buyer chose, not only the first.
        //
        // This took one conversion_action and switched every other category
        // off, so a campaign could optimise toward exactly one thing. Buyers
        // routinely want two - a purchase and a lead, a signup and a call - and
        // Google supports it: campaign_conversion_goal is per category, and any
        // number of them may be biddable at once. conversion_actions carries
        // the full set and conversion_action stays as the first of it, so
        // anything still passing one value keeps working.
        $actions = array_values(array_filter(array_map(
            'strval',
            (array) ($data['conversion_actions'] ?? array_filter([$data['conversion_action'] ?? null])),
        )));

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

        $categories = array_values(array_unique(array_filter(array_map(
            fn (string $action): ?string => $this->conversionActionCategory($connection, $action),
            $actions,
        ))));

        // None of them resolved, so there is nothing to narrow toward. Leaving
        // the goals alone is the documented behaviour: a campaign counting more
        // conversions than asked still spends sensibly, one counting none
        // cannot optimise at all.
        if ($categories === []) {
            return;
        }

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

        $goals = $this->search(
            $connection,
            'SELECT campaign_conversion_goal.category, campaign_conversion_goal.origin, '
            .'campaign_conversion_goal.biddable FROM campaign_conversion_goal WHERE campaign.id = '.$campaignId,
            $customerId,
        );

        $operations = [];

        foreach (data_get($goals, '0.results', []) as $goal) {
            $goalCategory = (string) data_get($goal, 'campaignConversionGoal.category');
            $origin = (string) data_get($goal, 'campaignConversionGoal.origin');

            if ($goalCategory === '' || $origin === '') {
                continue;
            }

            $wanted = in_array($goalCategory, $categories, true);

            // Absent means false, which is how Google reports a goal that is
            // off, so the comparison is against true rather than to a cast.
            if ($wanted === (data_get($goal, 'campaignConversionGoal.biddable') === true)) {
                continue;
            }

            $operations[] = ['update' => [
                'resourceName' => sprintf(
                    'customers/%s/campaignConversionGoals/%s~%s~%s',
                    $customerId,
                    $campaignId,
                    $goalCategory,
                    $origin,
                ),
                'biddable' => $wanted,
            ], 'updateMask' => 'biddable'];
        }

        if ($operations !== []) {
            $this->mutateMany($connection, 'campaignConversionGoals', $operations);
        }
    }

    /** The category of one conversion action, or null if it is not on the account. */
    private function conversionActionCategory(GoogleAdsConnection $connection, string $resourceName): ?string
    {
        foreach ($this->conversionActionOptions($connection) as $option) {
            if (($option['resource_name'] ?? null) === $resourceName) {
                return $option['category'] ?? null;
            }
        }

        return null;
    }

    /**
     * Google's tracking template, as a campaign field or nothing at all.
     *
     * Spread into the create rather than set to null, because Google rejects a
     * null trackingUrlTemplate where it accepts the field being absent.
     *
     * @param  array<string,mixed>  $data
     * @return array<string,string>
     */
    private function trackingTemplateField(array $data): array
    {
        $template = trim((string) ($data['tracking_url_template'] ?? ''));

        return $template === '' ? [] : ['trackingUrlTemplate' => $template];
    }

    /** Google takes money in millionths of the account's currency unit. */
    private function micros(?float $amount): int
    {
        return (int) round((float) $amount * 1_000_000);
    }

    /**
     * Remove a resource, and say so if it did not happen.
     *
     * This caught everything and reported it, which made every caller's success
     * check meaningless: a refusal looked exactly like a removal. GooglePublisher
     * ::rollBack is written on top of it and says in as many words that
     * "removeResource throws on a refusal rather than reporting one, so reaching
     * here means both removals were accepted" - which was not true, so it always
     * returned "nothing left behind" however the removal went. The contract that
     * return value serves is the one Publisher records on the decision so a
     * buyer can be told what is still on their account.
     *
     * DeleteEntity's own notes describe where that ends: a cleanup cleared local
     * ids "on the strength of a rollback that reported success having done
     * nothing, which left five live Google campaigns with no record here at
     * all". The swallow is that bug, and it outlived the write-up of it.
     *
     * Throwing rather than returning a boolean, because every caller here is
     * already inside a try and a silent false is how this went wrong once.
     *
     * The swallow had a reason, recorded where it stood: "a rollback that fails
     * must leave the original error as the one the user is told about". That
     * still holds and is still satisfied - rollBack catches each removal
     * separately, so the publish error it was called for stays the one raised,
     * and what could not be removed is returned instead of discarded.
     *
     * Google's mutate takes a resource name rather than a bare id, so the caller
     * passes back what create returned.
     */
    public function removeResource(GoogleAdsConnection $connection, string $resource, string $collection): void
    {
        $this->mutate($connection, $collection, ['remove' => $resource]);
    }

    /**
     * The Google device types this campaign should not reach.
     *
     * Empty when every device was chosen, or when nobody chose: Google's
     * default is all of them, so excluding nothing is the right no-op rather
     * than something to guess at.
     *
     * @param  array<string,mixed>  $data
     * @return list<string>
     */
    private function devicesToExclude(array $data): array
    {
        $chosen = array_map('strtolower', $this->targetingValues($data['devices'] ?? null));

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

        $wanted = [
            'MOBILE' => in_array('mobile', $chosen, true),
            'TABLET' => in_array('mobile', $chosen, true),
            'DESKTOP' => in_array('desktop', $chosen, true),
        ];

        // Every device unwanted means the answer was not understood, and a
        // campaign excluded from everything reaches nobody. Better to target
        // all of them than to silently build one that cannot deliver.
        if (! in_array(true, $wanted, true)) {
            return [];
        }

        return array_keys(array_filter($wanted, fn (bool $keep): bool => ! $keep));
    }

    private function addTargetingCriteria(GoogleAdsConnection $connection, string $campaignResource, array $data): void
    {
        $operations = [];
        $locationScope = (string) ($data['location_scope'] ?? '');
        $locations = $this->targetingValues($data['locations'] ?? null);
        if ($locations === [] && $locationScope !== '') {
            $locations = match ($locationScope) {
                'us_ca' => ['US', 'CA'],
                'us' => ['US'],
                'all' => [],
                default => $locations,
            };
        }

        foreach ($locations as $location) {
            $resource = str_starts_with($location, 'geoTargetConstants/')
                ? $location
                : $this->targetConstant($connection, 'geo_target_constant', $location);
            if ($resource !== null) {
                $operations[] = ['create' => [
                    'campaign' => $campaignResource,
                    'location' => ['geoTargetConstant' => $resource],
                ]];
            }
        }

        foreach ($this->targetingValues($data['excluded_locations'] ?? null) as $location) {
            if (! preg_match('/^geoTargetConstants\/[0-9]+$/D', $location)
                || in_array($location, $locations, true)) {
                throw new RuntimeException('A Google exclusion needs a verified place that is not also included.');
            }

            $operations[] = ['create' => [
                'campaign' => $campaignResource,
                'negative' => true,
                'location' => ['geoTargetConstant' => $location],
            ]];
        }

        foreach ((array) ($data['proximity_targets'] ?? []) as $proximity) {
            $latitude = $proximity['latitude'] ?? null;
            $longitude = $proximity['longitude'] ?? null;
            $radius = $proximity['radius'] ?? null;
            $unit = $proximity['radius_unit'] ?? null;

            if (! is_numeric($latitude) || ! is_numeric($longitude) || ! is_numeric($radius)
                || ! is_finite((float) $latitude) || ! is_finite((float) $longitude) || ! is_finite((float) $radius)
                || (float) $latitude <= -90 || (float) $latitude >= 90
                || (float) $longitude <= -180 || (float) $longitude >= 180
                || (float) $radius < 1 || (float) $radius > 50 || ! in_array($unit, ['km', 'mi'], true)) {
                throw new RuntimeException('Google proximity targeting needs confirmed coordinates and a radius of 1 to 50 km or mi.');
            }

            $operations[] = ['create' => [
                'campaign' => $campaignResource,
                'proximity' => [
                    'geoPoint' => [
                        'latitudeInMicroDegrees' => (int) round(((float) $latitude) * 1_000_000),
                        'longitudeInMicroDegrees' => (int) round(((float) $longitude) * 1_000_000),
                    ],
                    'radius' => (float) $radius,
                    'radiusUnits' => $unit === 'km' ? 'KILOMETERS' : 'MILES',
                ],
            ]];
        }

        // Devices, which were collected by the chat and thrown away here.
        //
        // Google does not target devices, it un-targets them: every campaign
        // reaches desktop, mobile and tablet from the moment it exists, and the
        // only way to narrow that is a bid modifier of 0 on the ones not
        // wanted. Confirmed against the live account rather than assumed: a
        // criterion carrying "negative": true is refused with IMMUTABLE_FIELD,
        // and the same criterion with "bidModifier": 0 is accepted.
        //
        // Tablets go with mobile. Our vocabulary has only the two, Meta groups
        // them that way, and a buyer asking for mobile means a phone in a hand
        // rather than a phone and not a tablet. Connected TV is left alone: it
        // is outside the two words anyone chose between, and excluding it would
        // be a decision nobody made.
        foreach ($this->devicesToExclude($data) as $device) {
            $operations[] = ['create' => [
                'campaign' => $campaignResource,
                'device' => ['type' => $device],
                'bidModifier' => 0,
            ]];
        }

        foreach ($this->targetingValues($data['languages'] ?? null) as $language) {
            $resource = str_starts_with($language, 'languageConstants/')
                ? $language
                : $this->targetConstant($connection, 'language_constant', $language);
            if ($resource !== null) {
                $operations[] = ['create' => [
                    'campaign' => $campaignResource,
                    'language' => ['languageConstant' => $resource],
                ]];
            }
        }
        if ($operations !== []) {
            $this->mutateMany($connection, 'campaignCriteria', $operations);
        }
    }

    private function targetingValues(mixed $value): array
    {
        if (is_array($value)) {
            return array_values(array_filter(array_map(fn ($entry): string => trim((string) $entry), $value)));
        }

        if (blank($value)) {
            return [];
        }

        return array_values(array_filter(array_map('trim', explode(',', (string) $value))));
    }

    /**
     * A value going inside single quotes in a GAQL query.
     *
     * The backslash is escaped as well as the quote, and in one pass.
     *
     * This escaped the quote and left the escape character alone, so a name
     * ending in a backslash-quote closed the literal anyway: the \\' became an
     * escaped backslash followed by a live quote, and everything after it was
     * parsed as GAQL against the live ad account. Locations and languages reach
     * here from the chat, so the value is a stranger's.
     *
     * strtr rather than str_replace with arrays, because str_replace applies
     * its pairs in sequence and the second pass would escape the backslashes
     * the first had just written. GAQL has no bind parameters, so this is the
     * whole defence.
     */
    private function escapeGaqlLiteral(string $value): string
    {
        return strtr($value, ['\\' => '\\\\', "'" => "\\'"]);
    }

    private function targetConstant(GoogleAdsConnection $connection, string $resourceType, string $name): ?string
    {
        $escapedName = $this->escapeGaqlLiteral($name);
        $field = $resourceType === 'geo_target_constant'
            ? 'geo_target_constant.resource_name'
            : 'language_constant.resource_name';
        $response = $this->search($connection, "SELECT {$field} FROM {$resourceType} WHERE {$resourceType}.name = '{$escapedName}'");
        $resultKey = $resourceType === 'geo_target_constant' ? 'geoTargetConstant' : 'languageConstant';

        return data_get($response, '0.results.0.'.$resultKey.'.resourceName');
    }

    /** @return list<array{resource_name: string, name: string, category: string, type: string}> */
    public function conversionActionOptions(GoogleAdsConnection $connection): array
    {
        $response = $this->search($connection, 'SELECT conversion_action.resource_name, conversion_action.name, conversion_action.category, conversion_action.type FROM conversion_action WHERE conversion_action.status = ENABLED');

        return collect($response)
            ->flatMap(fn (array $chunk): array => $chunk['results'] ?? [])
            ->map(function (array $result): ?array {
                $action = $result['conversionAction'] ?? [];
                $resourceName = $action['resourceName'] ?? null;
                if (! is_string($resourceName) || $resourceName === '') {
                    return null;
                }

                return [
                    'resource_name' => $resourceName,
                    'name' => (string) ($action['name'] ?? 'Unnamed conversion action'),
                    'category' => (string) ($action['category'] ?? 'UNSPECIFIED'),
                    'type' => (string) ($action['type'] ?? 'UNSPECIFIED'),
                ];
            })
            ->filter()
            ->values()
            ->all();
    }

    /**
     * Daily campaign metrics for performance ingest. Does not mutate.
     *
     * @return list<array<string, mixed>>
     */
    public function readCampaignMetrics(
        GoogleAdsConnection $connection,
        string $googleCampaignId,
        string $since,
        string $until,
    ): array {
        $campaignId = preg_replace('/\D/', '', $googleCampaignId) ?? '';

        if ($campaignId === '') {
            throw new RuntimeException('Google campaign id is missing.');
        }

        if (! preg_match('/^\d{4}-\d{2}-\d{2}$/', $since) || ! preg_match('/^\d{4}-\d{2}-\d{2}$/', $until)) {
            throw new RuntimeException('Invalid metrics date range.');
        }

        $query = <<<GAQL
SELECT
  campaign.id,
  campaign.name,
  campaign.status,
  segments.date,
  metrics.impressions,
  metrics.clicks,
  metrics.cost_micros,
  metrics.ctr,
  metrics.average_cpc
FROM campaign
WHERE campaign.id = {$campaignId}
  AND segments.date BETWEEN '{$since}' AND '{$until}'
GAQL;

        $response = $this->search($connection, $query);

        return collect($response)
            ->flatMap(fn (mixed $chunk): array => is_array($chunk) ? ($chunk['results'] ?? []) : [])
            ->values()
            ->all();
    }

    /**
     * Hourly performance for a live Google campaign. Does not mutate.
     *
     * @return list<array<string, mixed>>
     */
    public function readCampaignHourlyMetrics(
        GoogleAdsConnection $connection,
        string $googleCampaignId,
        string $since,
        string $until,
    ): array {
        $campaignId = preg_replace('/\D/', '', $googleCampaignId) ?? '';

        if ($campaignId === '') {
            throw new RuntimeException('Google campaign id is missing.');
        }

        if (! preg_match('/^\d{4}-\d{2}-\d{2}$/', $since) || ! preg_match('/^\d{4}-\d{2}-\d{2}$/', $until)) {
            throw new RuntimeException('Invalid metrics date range.');
        }

        $query = <<<GAQL
SELECT
  campaign.id,
  campaign.name,
  campaign.status,
  segments.date,
  segments.hour,
  metrics.impressions,
  metrics.clicks,
  metrics.cost_micros,
  metrics.ctr,
  metrics.average_cpc
FROM campaign
WHERE campaign.id = {$campaignId}
  AND segments.date BETWEEN '{$since}' AND '{$until}'
GAQL;

        $response = $this->search($connection, $query);

        return collect($response)
            ->flatMap(fn (mixed $chunk): array => is_array($chunk) ? ($chunk['results'] ?? []) : [])
            ->values()
            ->all();
    }

    /**
     * Platform start date for a Google campaign. Does not mutate.
     */
    public function readCampaignStartDate(GoogleAdsConnection $connection, string $googleCampaignId): ?string
    {
        $campaignId = preg_replace('/\D/', '', $googleCampaignId) ?? '';

        if ($campaignId === '') {
            return null;
        }

        $query = <<<GAQL
SELECT
  campaign.id,
  campaign.start_date_time
FROM campaign
WHERE campaign.id = {$campaignId}
GAQL;

        try {
            $response = $this->search($connection, $query);
        } catch (RuntimeException) {
            return null;
        }

        $row = collect($response)
            ->flatMap(fn (mixed $chunk): array => is_array($chunk) ? ($chunk['results'] ?? []) : [])
            ->first();

        $dateTime = data_get($row, 'campaign.startDateTime') ?? data_get($row, 'campaign.start_date_time');
        $date = is_string($dateTime) ? substr($dateTime, 0, 10) : null;

        return is_string($date) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) === 1
            ? $date
            : null;
    }

    /**
     * Campaign metadata for performance profiles. Does not mutate.
     *
     * @return array<string, mixed>
     */
    public function readCampaignProfile(GoogleAdsConnection $connection, string $googleCampaignId, bool $fresh = false): array
    {
        $campaignId = preg_replace('/\D/', '', $googleCampaignId) ?? '';

        if ($campaignId === '') {
            throw new RuntimeException('Google campaign id is missing.');
        }

        $query = <<<GAQL
SELECT
  campaign.id,
  campaign.name,
  campaign.status,
  campaign.advertising_channel_type,
  campaign.start_date_time,
  campaign.end_date_time,
  customer.time_zone,
  campaign.primary_status,
  campaign.primary_status_reasons,
  campaign.bidding_strategy_type,
  campaign.bidding_strategy,
  campaign.maximize_conversions.target_cpa_micros,
  campaign.maximize_conversion_value.target_roas,
  campaign.target_cpa.target_cpa_micros,
  campaign.target_roas.target_roas,
  campaign.frequency_caps,
  campaign.network_settings.target_google_search,
  campaign.network_settings.target_search_network,
  campaign.network_settings.target_content_network,
  campaign.network_settings.target_partner_search_network,
  campaign.geo_target_type_setting.positive_geo_target_type,
  campaign.geo_target_type_setting.negative_geo_target_type,
  campaign_budget.resource_name,
  campaign_budget.reference_count,
  campaign_budget.amount_micros
FROM campaign
WHERE campaign.id = {$campaignId}
GAQL;

        try {
            $response = $this->search($connection, $query, fresh: $fresh);
        } catch (RuntimeException) {
            // The fallback is the profile as it was before run dates, the
            // account's zone and bidding were read, so none can cost the rest.
            $response = $this->search($connection, (string) preg_replace('/^  (campaign\.(start_date_time|end_date_time|bidding_strategy\w*|maximize_\w+\.\w+|target_(cpa|roas)\.\w+)|customer\.time_zone),\n/m', '', $query), fresh: $fresh);
        }

        $row = collect($response)
            ->flatMap(fn (mixed $chunk): array => is_array($chunk) ? ($chunk['results'] ?? []) : [])
            ->first();

        if (! is_array($row)) {
            throw new RuntimeException('Google campaign profile could not be loaded.');
        }

        $amountMicros = data_get($row, 'campaignBudget.amountMicros')
            ?? data_get($row, 'campaign_budget.amount_micros');
        $goalError = null;
        try {
            $goals = $this->readManagerGoals($connection, $campaignId);
        } catch (RuntimeException $exception) {
            report($exception);
            $goals = null;
            $goalError = $exception->getMessage();
        }

        return [
            'id' => (string) (data_get($row, 'campaign.id') ?? $campaignId),
            'name' => (string) data_get($row, 'campaign.name', ''),
            'status' => (string) data_get($row, 'campaign.status', ''),
            'advertising_channel_type' => (string) (data_get($row, 'campaign.advertisingChannelType')
                ?? data_get($row, 'campaign.advertising_channel_type')
                ?? ''),
            'start_date' => ($startDateTime = data_get($row, 'campaign.startDateTime')
                ?? data_get($row, 'campaign.start_date_time')) && preg_match('/^\d{4}-\d{2}-\d{2}/', (string) $startDateTime)
                ? substr((string) $startDateTime, 0, 10)
                : '',
            // As Google reports them: "2026-10-07 00:00:00" in the account's zone.
            'start_date_time' => (string) (data_get($row, 'campaign.startDateTime') ?? data_get($row, 'campaign.start_date_time') ?? ''),
            'end_date_time' => (string) (data_get($row, 'campaign.endDateTime') ?? data_get($row, 'campaign.end_date_time') ?? ''),
            'time_zone' => (string) (data_get($row, 'customer.timeZone') ?? data_get($row, 'customer.time_zone') ?? ''),
            'primary_status' => (string) (data_get($row, 'campaign.primaryStatus')
                ?? data_get($row, 'campaign.primary_status')
                ?? ''),
            'primary_status_reasons' => data_get($row, 'campaign.primaryStatusReasons')
                ?? data_get($row, 'campaign.primary_status_reasons')
                ?? [],
            'daily_budget' => is_numeric($amountMicros)
                ? round(((float) $amountMicros) / 1_000_000, 2)
                : null,
            'budget_resource' => (string) (data_get($row, 'campaignBudget.resourceName')
                ?? data_get($row, 'campaign_budget.resource_name')
                ?? ''),
            'budget_reference_count' => ($referenceCount = data_get($row, 'campaignBudget.referenceCount')
                ?? data_get($row, 'campaign_budget.reference_count')) !== null
                ? (int) $referenceCount
                : null,
            'bidding_strategy_type' => (string) (data_get($row, 'campaign.biddingStrategyType')
                ?? data_get($row, 'campaign.bidding_strategy_type')
                ?? ''),
            'bidding_portfolio' => (string) (data_get($row, 'campaign.biddingStrategy')
                ?? data_get($row, 'campaign.bidding_strategy')
                ?? ''),
            'target_cpa' => is_numeric($cpaMicros = data_get($row, 'campaign.maximizeConversions.targetCpaMicros')
                ?? data_get($row, 'campaign.targetCpa.targetCpaMicros'))
                && (float) $cpaMicros > 0
                ? round(((float) $cpaMicros) / 1_000_000, 2)
                : null,
            'target_roas' => is_numeric($roas = data_get($row, 'campaign.maximizeConversionValue.targetRoas')
                ?? data_get($row, 'campaign.targetRoas.targetRoas'))
                && (float) $roas > 0
                ? (float) $roas
                : null,
            'frequency_caps' => data_get($row, 'campaign.frequencyCaps', []),
            'network_settings' => is_array($networks = data_get($row, 'campaign.networkSettings'))
                ? array_replace(array_fill_keys(['targetGoogleSearch', 'targetSearchNetwork', 'targetContentNetwork', 'targetPartnerSearchNetwork'], false), $networks)
                : null,
            'geo_target_type' => data_get($row, 'campaign.geoTargetTypeSetting'),
            'conversion_goals' => $goals['selection'] ?? null,
            'manager_conversion_goals' => $goals['available'] ?? null,
            'conversion_goals_error' => $goalError,
        ];
    }

    /**
     * What a published Google campaign is made of: ad groups, ads, asset groups.
     *
     * The read behind list_campaign_structure, which could only answer for Meta.
     * Nothing here could answer it at all: app/Mcp/Tools/GoogleAds/ListAdGroups
     * and ListAds call $googleAds->listAdGroups() and ->listAds(), and neither
     * method has ever existed on this class - they are unregistered tools
     * written against an imagined API, so the first call would have been a
     * fatal, not an empty list. Hence a fresh read rather than a wiring job.
     *
     * Unlike readCampaignSearchCriteria, an incomplete row is not fatal here.
     * That method imports a baseline the product then edits, so a half-read
     * keyword would be written back wrongly and must cancel the import. This
     * one is read out to a person and acted on by id, where dropping the name
     * of one ad group is a worse answer but a safe one, and refusing to list
     * anything because a single row came back odd is the worse failure.
     *
     * Asset groups are queried only when they can exist - Performance Max keeps
     * its ads there and has no ad groups to find, so an empty first result is
     * what says to look. A Search campaign never pays for the third call.
     *
     * @return array{channel_type: string, ad_groups: list<array<string, mixed>>, ads: list<array<string, mixed>>, asset_groups: list<array<string, mixed>>}
     */
    public function readCampaignStructure(GoogleAdsConnection $connection, string $googleCampaignId, ?string $adGroupId = null): array
    {
        if (! preg_match('/^[0-9]+$/D', $googleCampaignId)) {
            throw new RuntimeException('Google campaign id must be numeric.');
        }

        if ($adGroupId !== null && ! preg_match('/^[0-9]+$/D', $adGroupId)) {
            throw new RuntimeException('Google ad group id must be numeric.');
        }

        $groupRows = $this->searchRows($connection, <<<GAQL
SELECT
  ad_group.id,
  ad_group.name,
  ad_group.status,
  ad_group.type,
  ad_group.cpc_bid_micros,
  campaign.advertising_channel_type
FROM ad_group
WHERE campaign.id = {$googleCampaignId}
  AND ad_group.status != 'REMOVED'
GAQL);

        $channelType = (string) (collect($groupRows)
            ->map(static fn (array $row): mixed => data_get($row, 'campaign.advertisingChannelType'))
            ->first(static fn (mixed $type): bool => is_string($type) && $type !== '') ?? '');

        $adGroups = collect($groupRows)
            ->map(static fn (array $row): array => [
                'id' => (string) (data_get($row, 'adGroup.id') ?? ''),
                'name' => (string) (data_get($row, 'adGroup.name') ?? ''),
                'status' => (string) (data_get($row, 'adGroup.status') ?? ''),
                'type' => (string) (data_get($row, 'adGroup.type') ?? ''),
                'cpc_bid' => is_numeric($bid = data_get($row, 'adGroup.cpcBidMicros'))
                    ? round(((float) $bid) / 1_000_000, 2)
                    : null,
            ])
            ->filter(static fn (array $group): bool => $group['id'] !== '')
            ->values()
            ->all();

        // Scoped on the ad group rather than the campaign when one is named, so
        // a buyer asking about one ad group does not pay to read every ad.
        $adFilter = $adGroupId !== null
            ? "ad_group.id = {$adGroupId}"
            : "campaign.id = {$googleCampaignId}";

        $ads = collect($this->searchRows($connection, <<<GAQL
SELECT
  ad_group_ad.ad.id,
  ad_group_ad.ad.name,
  ad_group_ad.status,
  ad_group_ad.policy_summary.approval_status,
  ad_group_ad.ad.responsive_search_ad.headlines,
  ad_group.id,
  ad_group.name
FROM ad_group_ad
WHERE {$adFilter}
  AND ad_group_ad.status != 'REMOVED'
GAQL))
            ->map(static function (array $row): array {
                $headlines = data_get($row, 'adGroupAd.ad.responsiveSearchAd.headlines');

                return [
                    'id' => (string) (data_get($row, 'adGroupAd.ad.id') ?? ''),
                    'name' => (string) (data_get($row, 'adGroupAd.ad.name') ?? ''),
                    'status' => (string) (data_get($row, 'adGroupAd.status') ?? ''),
                    // Google's nearest thing to Meta's effective_status: an ad
                    // can be ENABLED and still serve nothing while disapproved.
                    'approval_status' => (string) (data_get($row, 'adGroupAd.policySummary.approvalStatus') ?? ''),
                    'ad_group_id' => (string) (data_get($row, 'adGroup.id') ?? ''),
                    'ad_group' => (string) (data_get($row, 'adGroup.name') ?? ''),
                    'headline' => is_array($headlines)
                        ? (string) (data_get($headlines, '0.text') ?? '')
                        : '',
                ];
            })
            ->filter(static fn (array $ad): bool => $ad['id'] !== '')
            ->values()
            ->all();

        return [
            'channel_type' => $channelType,
            // Keywords hang off the ad group, and on a Search campaign they are
            // most of what an ad group is. edit_entity asks for a complete set
            // rather than a diff, so there has to be somewhere to read the
            // current one; this is it. One query for the whole campaign, and
            // none at all where there are no ad groups to hang them off.
            'ad_groups' => $adGroups === []
                ? []
                : $this->withKeywords($connection, $googleCampaignId, $adGroups),
            'ads' => $ads,
            'asset_groups' => $adGroups === [] && $adGroupId === null
                ? $this->readAssetGroups($connection, $googleCampaignId)
                : [],
        ];
    }

    /**
     * Each ad group with the keywords that sit on it.
     *
     * @param  list<array<string, mixed>>  $adGroups
     * @return list<array<string, mixed>>
     */
    private function withKeywords(GoogleAdsConnection $connection, string $googleCampaignId, array $adGroups): array
    {
        $byAdGroup = [];

        foreach ($this->searchRows($connection, <<<GAQL
SELECT
  ad_group.id,
  ad_group_criterion.keyword.text,
  ad_group_criterion.keyword.match_type,
  ad_group_criterion.negative
FROM ad_group_criterion
WHERE campaign.id = {$googleCampaignId}
  AND ad_group_criterion.type = 'KEYWORD'
  AND ad_group_criterion.status != 'REMOVED'
GAQL) as $row) {
            $text = (string) (data_get($row, 'adGroupCriterion.keyword.text') ?? '');
            $group = (string) (data_get($row, 'adGroup.id') ?? '');

            if ($text === '' || ! in_array($group, array_column($adGroups, 'id'), true)
                || ! in_array(data_get($row, 'adGroupCriterion.keyword.matchType'), ['BROAD', 'PHRASE', 'EXACT'], true)
                || ! is_bool(data_get($row, 'adGroupCriterion.negative', false))) {
                throw new RuntimeException('Google returned incomplete or unrelated Search keywords. The editable baseline was not replaced.');
            }

            $byAdGroup[$group][] = [
                'text' => $text,
                'match_type' => (string) (data_get($row, 'adGroupCriterion.keyword.matchType') ?? ''),
                'negative' => data_get($row, 'adGroupCriterion.negative') === true,
            ];
        }

        return array_map(
            static fn (array $group): array => [...$group, 'keywords' => $byAdGroup[$group['id']] ?? []],
            $adGroups,
        );
    }

    /**
     * What each of these has ever spent and shown, for the delete guard.
     *
     * All-time, which is what no date segment means in GAQL - verified against
     * the live account, where the campaign from conversation 01a13a0d reads
     * cost_micros 0 and impressions 0 while its neighbours read 143222716 and
     * 7759. A date range here would be the bug: a campaign that spent and then
     * stopped would read zero and be deleted as if it had never run.
     *
     * One query per level rather than one per id, because the guard runs on
     * every delete and the ids are already bounded to ten.
     *
     * @param  'campaign'|'ad_group'|'ad'  $level
     * @param  list<string>  $ids
     * @return array<string, array{spend: float, impressions: int}>
     */
    public function readLifetimeDelivery(GoogleAdsConnection $connection, string $level, array $ids): array
    {
        if ($ids === [] || count($ids) > 10 || ! array_is_list($ids)
            || array_filter($ids, fn (mixed $id): bool => ! is_string($id) || ! ctype_digit($id)) !== []) {
            throw new RuntimeException('Choose one to ten numeric Google entity IDs for lifetime reporting.');
        }

        $list = implode(', ', $ids);

        [$from, $idField, $path] = match ($level) {
            'ad_group' => ['ad_group', 'ad_group.id', 'adGroup.id'],
            'ad' => ['ad_group_ad', 'ad_group_ad.ad.id', 'adGroupAd.ad.id'],
            'campaign' => ['campaign', 'campaign.id', 'campaign.id'],
            default => throw new RuntimeException('Choose campaign, ad_group or ad lifetime reporting.'),
        };

        $rows = $this->searchRows($connection, <<<GAQL
SELECT
  {$idField},
  metrics.cost_micros,
  metrics.impressions
FROM {$from}
WHERE {$idField} IN ({$list})
GAQL);

        $delivery = [];

        foreach ($rows as $row) {
            $id = (string) (data_get($row, $path) ?? '');

            if (! in_array($id, $ids, true) || isset($delivery[$id]) || ! is_array($row['metrics'] ?? null)) {
                throw new RuntimeException('Google returned incomplete or unrelated lifetime delivery. Unknown spend is not zero.');
            }
            $micros = data_get($row, 'metrics.costMicros', 0);
            $impressions = data_get($row, 'metrics.impressions', 0);
            foreach ([$micros, $impressions] as $metric) {
                if ((! is_int($metric) && ! is_string($metric)) || ! preg_match('/^[0-9]+$/D', (string) $metric)) {
                    throw new RuntimeException('Google returned invalid lifetime delivery metrics.');
                }
                $digits = ltrim((string) $metric, '0');
                $maximum = (string) PHP_INT_MAX;
                if (strlen($digits) > strlen($maximum) || (strlen($digits) === strlen($maximum) && strcmp($digits, $maximum) > 0)) {
                    throw new RuntimeException('Google returned invalid lifetime delivery metrics.');
                }
            }
            $delivery[$id] = ['spend' => (float) $micros / 1_000_000, 'impressions' => (int) $impressions];
        }
        if (array_diff($ids, array_keys($delivery)) !== []) {
            throw new RuntimeException('Google did not confirm lifetime delivery for every requested object. Unknown spend is not zero.');
        }

        return $delivery;
    }

    /**
     * Change the keywords on an ad group that is already running.
     *
     * Nothing could do this. SearchKeywordSelections::save refuses a published
     * campaign outright - "available for draft Google Search campaigns only" -
     * and every other write to adGroupCriteria is inside the publish path. So
     * once a Search campaign went live nobody could add a term, drop one,
     * change a match type or add a negative, which is the most ordinary thing
     * a buyer does to a running Search campaign.
     *
     * Applied as a difference, not as a replacement. A keyword criterion
     * carries its own history and quality score, so removing and recreating
     * one that did not change would throw that away and restart it at nothing.
     * Only what actually differs is touched.
     *
     * Identity is text, match type and negative together, because Google treats
     * each combination as its own criterion: neither the match type nor the
     * negative flag can be updated in place, so a change to either is a removal
     * and an addition rather than an edit.
     *
     * Removals go first. The add and remove sets are disjoint by construction
     * so nothing should collide, but a term moving between match types is the
     * case where order would matter if that ever stopped being true.
     *
     * @param  list<array{text: string, match_type: string, negative: bool}>  $keywords
     * @return array{added: int, removed: int, unchanged: int}
     */
    public function replaceAdGroupKeywords(GoogleAdsConnection $connection, string $adGroupId, array $keywords): array
    {
        if (! preg_match('/^[0-9]+$/D', $adGroupId)) {
            throw new RuntimeException('Google ad group id must be numeric.');
        }

        $key = static fn (string $text, string $match, bool $negative): string => mb_strtolower(trim($text)).'|'.$match.'|'.($negative ? '1' : '0');

        $current = [];

        foreach ($this->searchRows($connection, <<<GAQL
SELECT
  ad_group_criterion.resource_name,
  ad_group_criterion.keyword.text,
  ad_group_criterion.keyword.match_type,
  ad_group_criterion.negative
FROM ad_group_criterion
WHERE ad_group.id = {$adGroupId}
  AND ad_group_criterion.type = 'KEYWORD'
  AND ad_group_criterion.status != 'REMOVED'
GAQL) as $row) {
            $text = (string) (data_get($row, 'adGroupCriterion.keyword.text') ?? '');
            $resource = (string) (data_get($row, 'adGroupCriterion.resourceName') ?? '');

            if ($text === '' || ! preg_match('/^customers\/'.$this->customerId($connection).'\/adGroupCriteria\/'.$adGroupId.'~[0-9]+$/D', $resource)
                || ! in_array(data_get($row, 'adGroupCriterion.keyword.matchType'), ['BROAD', 'PHRASE', 'EXACT'], true)) {
                throw new RuntimeException('Google returned incomplete or foreign keywords. Nothing was sent.');
            }

            $current[$key(
                $text,
                (string) (data_get($row, 'adGroupCriterion.keyword.matchType') ?? ''),
                data_get($row, 'adGroupCriterion.negative') === true,
            )] = $resource;
        }

        $wanted = [];

        foreach ($keywords as $keyword) {
            if (! is_array($keyword) || ! is_string($keyword['text'] ?? null) || trim($keyword['text']) === ''
                || mb_strlen($keyword['text']) > 80 || ! in_array($keyword['match_type'] ?? null, ['BROAD', 'PHRASE', 'EXACT'], true)
                || ! is_bool($keyword['negative'] ?? null)) {
                throw new RuntimeException('Choose valid native keyword text, match types and exclusion flags.');
            }
            $wanted[$key($keyword['text'], $keyword['match_type'], $keyword['negative'])] = $keyword;
        }

        $target = sprintf('customers/%s/adGroups/%s', $this->customerId($connection), $adGroupId);
        $removals = array_diff_key($current, $wanted);
        $additions = array_diff_key($wanted, $current);

        $operations = array_map(
            static fn (string $resource): array => ['remove' => $resource],
            array_values($removals),
        );
        array_push($operations, ...array_map(
            static fn (array $keyword): array => ['create' => [
                'adGroup' => $target,
                'status' => 'ENABLED',
                'negative' => $keyword['negative'],
                'keyword' => ['text' => $keyword['text'], 'matchType' => $keyword['match_type']],
            ]],
            array_values($additions),
        ));
        if ($operations !== []) {
            $this->mutateMany($connection, 'adGroupCriteria', $operations, ['partialFailure' => false]);
        }

        return [
            'added' => count($additions),
            'removed' => count($removals),
            'unchanged' => count(array_intersect_key($current, $wanted)),
        ];
    }

    /**
     * Copy a live ad group, with its keywords and optionally its ads.
     *
     * Google has no copy operation, so this is a read of the source followed by
     * creates. Everything lands PAUSED, like everything else this product
     * builds: a copy that starts spending the moment it exists is not a copy of
     * a decision anybody made.
     *
     * cpcBidMicros is carried only under manual CPC. The publish path already
     * records why - Google refuses the field with
     * OPERATION_NOT_PERMITTED_FOR_CONTEXT when the campaign uses Smart Bidding -
     * and a copy is the one place it would otherwise be carried over blindly
     * from a source that predates a bidding change.
     *
     * A half-built copy is worse than none, so a failure after the ad group
     * exists tries to remove it and says so if that did not work either.
     *
     * @return array{ad_group_id: string, keywords: int, ads: list<string>}
     */
    public function duplicateAdGroup(
        GoogleAdsConnection $connection,
        string $adGroupId,
        ?string $name = null,
        bool $withAds = true,
        ?string $targetCampaign = null,
        ?string $expectedCampaignId = null,
    ): array {
        if (! preg_match('/^[0-9]+$/D', $adGroupId)) {
            throw new RuntimeException('Google ad group id must be numeric.');
        }

        $sources = $this->searchRows($connection, <<<GAQL
SELECT
  ad_group.id,
  ad_group.name,
  ad_group.type,
  ad_group.cpc_bid_micros,
  ad_group.campaign,
  ad_group.tracking_url_template,
  ad_group.final_url_suffix,
  ad_group.url_custom_parameters,
  ad_group.targeting_setting.target_restrictions,
  ad_group.excluded_parent_asset_field_types,
  ad_group.excluded_parent_asset_set_types,
  ad_group.display_custom_bid_dimension,
  ad_group.audience_setting.use_audience_grouped,
  ad_group.optimized_targeting_enabled,
  ad_group.ad_rotation_mode,
  ad_group.cpm_bid_micros,
  ad_group.cpv_bid_micros,
  ad_group.target_cpa_micros,
  ad_group.target_roas,
  campaign.bidding_strategy_type
FROM ad_group
WHERE ad_group.id = {$adGroupId}
  AND ad_group.status != 'REMOVED'
GAQL);
        $source = count($sources) === 1 ? $sources[0] : null;

        if (! is_array($source) || (string) data_get($source, 'adGroup.id') !== $adGroupId) {
            throw new RuntimeException('That ad group could not be read, so nothing was copied.');
        }

        $campaignResource = (string) (data_get($source, 'adGroup.campaign') ?? '');

        if ($campaignResource === '') {
            throw new RuntimeException('Google did not say which campaign that ad group belongs to.');
        }
        $customer = $this->customerId($connection);
        if (! preg_match('/^customers\/'.$customer.'\/campaigns\/[0-9]+$/D', $campaignResource)
            || ($expectedCampaignId !== null && $campaignResource !== "customers/{$customer}/campaigns/{$expectedCampaignId}")
            || ($targetCampaign !== null && ! preg_match('/^customers\/'.$customer.'\/campaigns\/[0-9]+$/D', $targetCampaign))) {
            throw new RuntimeException('Google returned an ad group outside the expected campaign or account.');
        }
        if (! in_array(data_get($source, 'adGroup.type'), ['SEARCH_STANDARD', 'DISPLAY_STANDARD'], true)) {
            throw new RuntimeException('Only standard Search and Display ad groups can be reconstructed without specialized settings.');
        }

        $expectedAdCount = $withAds ? $this->copyableAdCount($connection, $adGroupId) : 0;
        $strategy = data_get($source, 'campaign.biddingStrategyType');
        $criterionPayloads = $this->copyCriterionPayloads($connection, 'ad_group', $adGroupId, $strategy);
        $modifiers = $this->copyAdGroupModifierPlan($connection, $adGroupId);
        $this->assertCopyRelationsSupported($connection, 'ad_group', $adGroupId);
        $links = [
            'adGroupAssets' => ['ad_group_asset', ['asset', 'field_type', 'status']],
            'adGroupAssetSets' => ['ad_group_asset_set', ['asset_set', 'status']],
        ];
        $linkPayloads = [];
        foreach ($links as $collection => [$native, $fields]) {
            $linkPayloads[$collection] = $this->copyLinkPayloads($connection, $native, $adGroupId, $fields, 'ad_group');
        }

        $create = [
            'campaign' => $targetCampaign ?? $campaignResource,
            'name' => $name !== null && trim($name) !== ''
                ? trim($name)
                : mb_substr((string) (data_get($source, 'adGroup.name') ?? 'Ad group'), 0, 248).' (copy)',
            'status' => 'PAUSED',
            'type' => (string) (data_get($source, 'adGroup.type') ?? 'SEARCH_STANDARD'),
        ];
        $create = [...array_intersect_key($source['adGroup'], array_flip([
            'trackingUrlTemplate', 'finalUrlSuffix', 'urlCustomParameters', 'targetingSetting', 'optimizedTargetingEnabled',
            'adRotationMode',
            'excludedParentAssetFieldTypes', 'excludedParentAssetSetTypes', 'displayCustomBidDimension', 'audienceSetting',
        ])), ...$create];

        $create = [...$create, ...$this->copyBidOverrides($source['adGroup'], $strategy)];
        $create = $this->copyMessageContainers($create);

        $resource = $this->firstResourceName($this->mutate($connection, 'adGroups', ['create' => $create]), 'adGroupResult');

        if (! is_string($resource) || ! preg_match('/^customers\/'.$customer.'\/adGroups\/[0-9]+$/D', $resource)
            || $resource === "customers/{$customer}/adGroups/{$adGroupId}") {
            throw new RuntimeException('Google Ads did not return the copied ad group.');
        }

        try {
            $keywords = count(array_filter($criterionPayloads, fn (array $criterion): bool => isset($criterion['keyword'])));
            if ($criterionPayloads !== []) {
                $this->mutateMany($connection, 'adGroupCriteria', array_map(
                    fn (array $criterion): array => ['create' => [...$criterion, 'adGroup' => $resource]], $criterionPayloads,
                ), ['partialFailure' => false]);
            }
            foreach ($linkPayloads as $collection => $objects) {
                if ($objects !== []) {
                    $this->mutateMany($connection, $collection, array_map(
                        fn (array $object): array => ['create' => [...$object, 'adGroup' => $resource]], $objects,
                    ), ['partialFailure' => false]);
                }
            }
            $ads = $withAds ? $this->copyNativeAds($connection, $adGroupId, $resource) : [];
            if (count($ads) !== $expectedAdCount) {
                throw new RuntimeException('The source ads changed during reconstruction. The partial copy cannot be confirmed.');
            }
            $targetModifiers = $this->copyAdGroupModifierPlan($connection, $this->resourceId($resource));
            $modifierUpdates = [];
            foreach ($modifiers as $modifier) {
                $targetModifier = collect($targetModifiers)->firstWhere('device.type', $modifier['device']['type']);
                if ($targetModifier === null) {
                    throw new RuntimeException('Google did not report the copied group device modifiers.');
                }
                if ($targetModifier['bidModifier'] !== $modifier['bidModifier']) {
                    $modifierUpdates[] = ['update' => ['resourceName' => $targetModifier['resourceName'],
                        ...($modifier['bidModifier'] !== null ? ['bidModifier' => $modifier['bidModifier']] : [])], 'updateMask' => 'bid_modifier'];
                }
            }
            if ($modifierUpdates !== []) {
                $this->mutateMany($connection, 'adGroupBidModifiers', $modifierUpdates);
            }
            $withoutIds = fn (array $modifier): array => array_diff_key($modifier, ['resourceName' => true]);
            if ($this->copySet(array_map($withoutIds, $modifiers)) !== $this->copySet(array_map($withoutIds, $this->copyAdGroupModifierPlan($connection, $this->resourceId($resource))))) {
                throw new RuntimeException('Google did not confirm the copied device bid modifiers.');
            }
            $groupRows = $this->searchRows($connection, 'SELECT ad_group.id, ad_group.name, ad_group.status, ad_group.type, ad_group.campaign, ad_group.cpc_bid_micros, ad_group.cpm_bid_micros, ad_group.cpv_bid_micros, ad_group.target_cpa_micros, ad_group.target_roas, ad_group.tracking_url_template, ad_group.final_url_suffix, ad_group.url_custom_parameters, ad_group.targeting_setting.target_restrictions, ad_group.optimized_targeting_enabled, ad_group.ad_rotation_mode, ad_group.excluded_parent_asset_field_types, ad_group.excluded_parent_asset_set_types, ad_group.display_custom_bid_dimension, ad_group.audience_setting.use_audience_grouped FROM ad_group WHERE ad_group.id = '.$this->resourceId($resource));
            $this->assertCopiedFields($groupRows[0]['adGroup'] ?? [], $create);
            if ($this->copySet($this->copyCriterionPayloads($connection, 'ad_group', $this->resourceId($resource), $strategy)) !== $this->copySet($criterionPayloads)) {
                throw new RuntimeException('Google did not confirm all copied ad group criteria.');
            }
            foreach ($links as $collection => [$native, $fields]) {
                if ($this->copySet($linkPayloads[$collection]) !== $this->copySet($this->copyLinkPayloads($connection, $native, $this->resourceId($resource), $fields, 'ad_group'))) {
                    throw new RuntimeException('Google did not confirm the copied ad group asset links.');
                }
            }
        } catch (RuntimeException $e) {
            throw new RuntimeException($this->undo($connection, $resource, $e));
        }

        return ['ad_group_id' => $this->resourceId($resource), 'keywords' => $keywords, 'ads' => $ads];
    }

    /**
     * Copy one supported native ad, by default into its own ad group.
     *
     * @return string the new ad id
     */
    public function duplicateAd(GoogleAdsConnection $connection, string $adId, ?string $adGroupId = null, ?string $expectedSourceAdGroupId = null): string
    {
        if (! preg_match('/^[0-9]+$/D', $adId)) {
            throw new RuntimeException('Google ad id must be numeric.');
        }

        foreach ([$adGroupId, $expectedSourceAdGroupId] as $groupId) {
            if ($groupId !== null && ! preg_match('/^[0-9]+$/D', $groupId)) {
                throw new RuntimeException('Google ad group id must be numeric.');
            }
        }

        $fields = implode(', ', array_map(fn (string $field): string => 'ad_group_ad.ad.'.$field, self::COPY_AD_FIELDS));
        $filter = $expectedSourceAdGroupId !== null ? " AND ad_group.id = {$expectedSourceAdGroupId}" : '';
        $sources = $this->searchRows($connection, "SELECT {$fields}, ad_group.id, ad_group.resource_name FROM ad_group_ad WHERE ad_group_ad.ad.id = {$adId}{$filter} AND ad_group_ad.status != 'REMOVED'");
        if (count($sources) !== 1) {
            throw new RuntimeException('Google did not return exactly one source ad in the selected ad group.');
        }
        $source = $sources[0];

        if ((string) data_get($source, 'adGroupAd.ad.id') !== $adId
            || ! preg_match('/^customers\/'.$this->customerId($connection).'\/adGroups\/[0-9]+$/D', (string) data_get($source, 'adGroup.resourceName'))
            || ($expectedSourceAdGroupId !== null && data_get($source, 'adGroup.resourceName') !== 'customers/'.$this->customerId($connection).'/adGroups/'.$expectedSourceAdGroupId)) {
            throw new RuntimeException('Google returned an ad outside the selected source ad group.');
        }

        $target = $adGroupId !== null
            ? sprintf('customers/%s/adGroups/%s', $this->customerId($connection), $adGroupId)
            : (string) (data_get($source, 'adGroup.resourceName') ?? '');

        if (! preg_match('/^customers\/'.$this->customerId($connection).'\/adGroups\/[0-9]+$/D', $target)) {
            throw new RuntimeException('Google did not say which ad group that ad belongs to.');
        }

        return $this->resourceId($this->createCopiedAd($connection, $source, $target));
    }

    /** Validate every source creative before creating any copy. */
    private function copyableAdCount(GoogleAdsConnection $connection, string $adGroupId): int
    {
        // The id goes straight into GAQL, so it is checked here rather than
        // trusted from the caller. duplicateAdGroup does check first; a second
        // caller added later would not have to know that.
        if (! preg_match('/^[0-9]+$/D', $adGroupId)) {
            throw new RuntimeException('Google ad group id must be numeric.');
        }

        $ads = $this->copyAdRows($connection, $adGroupId);
        foreach ($ads as $row) {
            if (blank(data_get($row, 'adGroupAd.ad.responsiveSearchAd.headlines'))
                && blank(data_get($row, 'adGroupAd.ad.responsiveDisplayAd'))
                && blank(data_get($row, 'adGroupAd.ad.imageAd'))) {
                throw new RuntimeException('This ad group includes an unsupported creative format. Nothing was copied.');
            }
            $this->copiedAdPayload($row);
        }

        return count($ads);
    }

    /** @return list<string> */
    private function copyNativeAds(GoogleAdsConnection $connection, string $adGroupId, string $target): array
    {
        $ads = [];

        foreach ($this->copyAdRows($connection, $adGroupId) as $row) {
            $ads[] = $this->resourceId($this->createCopiedAd($connection, $row, $target));
        }

        return $ads;
    }

    /** @return list<array<string, mixed>> */
    private function copyAdRows(GoogleAdsConnection $connection, string $adGroupId): array
    {
        $fields = implode(', ', array_map(fn (string $field): string => 'ad_group_ad.ad.'.$field, self::COPY_AD_FIELDS));

        return $this->searchRows($connection, "SELECT {$fields}, ad_group.id FROM ad_group_ad WHERE ad_group.id = {$adGroupId} AND ad_group_ad.status != 'REMOVED'");
    }

    /**
     * One supported native ad, rebuilt from what was read off another.
     *
     * Pinned fields are carried with their assets. A pin is a decision about
     * where a headline may appear, so dropping it would quietly change what
     * Google is allowed to show.
     *
     * @param  array<string, mixed>  $source
     */
    private function copiedAdPayload(array $source): array
    {
        $native = $this->copyCreativeFields((array) data_get($source, 'adGroupAd.ad', []));
        $source['adGroupAd']['ad'] = $native;
        $ad = array_intersect_key($native, array_flip(['name', 'finalUrls', 'finalMobileUrls', 'trackingUrlTemplate', 'finalUrlSuffix', 'urlCustomParameters']));
        if (is_array($native['responsiveDisplayAd'] ?? null)) {
            $ad['responsiveDisplayAd'] = $native['responsiveDisplayAd'];
        } elseif (is_array($native['imageAd'] ?? null)) {
            $image = $native['imageAd'];
            $ad['imageAd'] = isset($image['imageAsset'])
                ? ['imageAsset' => $image['imageAsset']]
                : ['adIdToCopyImageFrom' => (string) ($native['id'] ?? '')];
        } else {
            $assets = static fn (string $field): array => collect((array) (data_get($source, 'adGroupAd.ad.responsiveSearchAd.'.$field) ?? []))
                ->map(static fn (mixed $asset): ?array => is_array($asset) && trim((string) ($asset['text'] ?? '')) !== ''
                    ? array_filter([
                        'text' => (string) $asset['text'],
                        'pinnedField' => $asset['pinnedField'] ?? null,
                    ], static fn (mixed $value): bool => $value !== null)
                    : null)
                ->filter()
                ->values()
                ->all();

            $headlines = $assets('headlines');
            $descriptions = $assets('descriptions');
            $finalUrls = array_values(array_filter((array) (data_get($source, 'adGroupAd.ad.finalUrls') ?? [])));

            if ($headlines === [] || $descriptions === [] || $finalUrls === []) {
                throw new RuntimeException('That ad has no readable headlines, descriptions or final URL, so it was not copied.');
            }

            $responsive = ['headlines' => $headlines, 'descriptions' => $descriptions];

            foreach (['path1', 'path2'] as $path) {
                if (filled($value = data_get($source, 'adGroupAd.ad.responsiveSearchAd.'.$path))) {
                    $responsive[$path] = (string) $value;
                }
                $ad['responsiveSearchAd'] = $responsive;
            }
            if (empty($ad['finalUrls'])) {
                throw new RuntimeException('Google did not report the final URLs needed to copy this ad.');
            }
        }

        return $ad;
    }

    /** @param array<string, mixed> $source */
    private function createCopiedAd(GoogleAdsConnection $connection, array $source, string $target): string
    {
        $ad = $this->copyMessageContainers($this->copiedAdPayload($source));
        $resource = $this->firstResourceName($this->mutate($connection, 'adGroupAds', [
            'create' => [
                'adGroup' => $target,
                'status' => 'PAUSED',
                'ad' => $ad,
            ],
        ]), 'adGroupAdResult');

        if (! is_string($resource) || ! preg_match('/^customers\/'.$this->customerId($connection).'\/adGroupAds\/'.$this->resourceId($target).'~[0-9]+$/D', $resource)
            || $this->resourceId($resource) === (string) data_get($source, 'adGroupAd.ad.id')) {
            throw new RuntimeException('Google Ads did not return the copied ad.');
        }
        try {
            $fields = implode(', ', array_map(fn (string $field): string => 'ad_group_ad.ad.'.$field, self::COPY_AD_FIELDS));
            $id = $this->resourceId($resource);
            $readback = $this->searchRows($connection, "SELECT {$fields}, ad_group_ad.status, ad_group.id, ad_group.resource_name FROM ad_group_ad WHERE ad_group_ad.ad.id = {$id} AND ad_group.id = ".$this->resourceId($target));
            if (count($readback) !== 1 || data_get($readback, '0.adGroupAd.status') !== 'PAUSED' || data_get($readback, '0.adGroup.resourceName') !== $target) {
                throw new RuntimeException('Google did not confirm the copied ad as PAUSED in the expected ad group.');
            }
            $expected = $ad;
            if (isset($expected['imageAd']['adIdToCopyImageFrom'])) {
                $expected['imageAd'] = ['imageUrl' => data_get($source, 'adGroupAd.ad.imageAd.imageUrl')];
            }
            $this->assertCopiedFields($this->copyCreativeFields(data_get($readback, '0.adGroupAd.ad', [])), $expected);
        } catch (Throwable $exception) {
            try {
                $this->removeResource($connection, $resource, 'adGroupAds');
            } catch (Throwable $cleanup) {
                report($cleanup);
                throw new RuntimeException($exception->getMessage().' Cleanup is incomplete; PAUSED ad remains: '.$resource, 0, $exception);
            }
            throw new RuntimeException($exception->getMessage().' Incomplete ad copy was removed.', 0, $exception);
        }

        return $resource;
    }

    /** @param array<array-key, mixed> $fields
     * @return array<array-key, mixed>
     */
    private function copyCreativeFields(array $fields): array
    {
        unset($fields['assetPerformanceLabel'], $fields['policySummaryInfo']);
        foreach ($fields as $key => $value) {
            if (is_array($value)) {
                $fields[$key] = $this->copyCreativeFields($value);
            }
        }

        return $fields;
    }

    /**
     * Take back a half-built copy, and say so plainly if that failed too.
     *
     * The message is the caller's, because an ad group left behind on the
     * account is something the buyer has to be told about rather than
     * something to log and move past.
     */
    private function undo(GoogleAdsConnection $connection, string $resource, RuntimeException $cause): string
    {
        try {
            $this->removeResource($connection, $resource, 'adGroups');
        } catch (Throwable $removal) {
            return $cause->getMessage()
                .' The copied ad group could not be removed either, so '.$resource
                .' is still on the account: '.$removal->getMessage();
        }

        return $cause->getMessage().' The partly built copy was removed.';
    }

    /**
     * Rename an ad group, or change what it bids.
     *
     * Only the two fields a buyer can act on at this level. The campaign holds
     * the budget and the bid strategy on Google - an ad group has neither - so
     * those stay with updateLiveCampaign, and asking for them here would be a
     * question with no answer rather than a missing feature.
     *
     * The update mask names only what was passed, so sending a name does not
     * blank a bid.
     *
     * @param  array{name?: string, cpc_bid?: float}  $fields
     */
    public function updateAdGroup(GoogleAdsConnection $connection, string $adGroupId, array $fields): void
    {
        if (! preg_match('/^[0-9]+$/D', $adGroupId)) {
            throw new RuntimeException('Google ad group id must be numeric.');
        }

        $update = [];
        $mask = [];

        if (filled($fields['name'] ?? null)) {
            $update['name'] = (string) $fields['name'];
            $mask[] = 'name';
        }

        if (isset($fields['cpc_bid']) && is_numeric($fields['cpc_bid'])) {
            $update['cpcBidMicros'] = (string) $this->micros((float) $fields['cpc_bid']);
            $mask[] = 'cpc_bid_micros';
        }

        if ($mask === []) {
            throw new RuntimeException('Nothing was given to change on the ad group.');
        }

        $this->mutate($connection, 'adGroups', [
            'update' => [
                'resourceName' => sprintf('customers/%s/adGroups/%s', $this->customerId($connection), $adGroupId),
                ...$update,
            ],
            'updateMask' => implode(',', $mask),
        ]);
    }

    /**
     * Remove one campaign, ad group or ad, by the name Google keys it under.
     *
     * An ad needs its ad group id for the same reason setChildStatus does: an
     * AdGroupAd is <adGroupId>~<adId>. Removing a campaign takes its ad groups
     * and ads with it, so they are not removed first - unlike Meta, which
     * refuses a parent that still has children.
     *
     * @param  'campaign'|'ad_group'|'ad'  $level
     */
    public function removeEntity(
        GoogleAdsConnection $connection,
        string $level,
        string $id,
        ?string $adGroupId = null,
    ): void {
        if ($level === 'ad' && blank($adGroupId)) {
            throw new RuntimeException('A Google ad cannot be addressed without its ad group id.');
        }

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

        [$collection, $resourceId] = match ($level) {
            'ad_group' => ['adGroups', $id],
            'ad' => ['adGroupAds', $adGroupId.'~'.$id],
            default => ['campaigns', $id],
        };

        $this->removeResource($connection, sprintf('customers/%s/%s/%s', $customerId, $collection, $resourceId), $collection);
    }

    /**
     * Performance Max keeps its creative in asset groups, which setLiveStatus
     * still cannot reach - listing them is what lets a buyer name one.
     *
     * @return list<array<string, mixed>>
     */
    private function readAssetGroups(GoogleAdsConnection $connection, string $googleCampaignId): array
    {
        return collect($this->searchRows($connection, <<<GAQL
SELECT
  asset_group.id,
  asset_group.name,
  asset_group.status,
  asset_group.primary_status
FROM asset_group
WHERE campaign.id = {$googleCampaignId}
  AND asset_group.status != 'REMOVED'
GAQL))
            ->map(static fn (array $row): array => [
                'id' => (string) (data_get($row, 'assetGroup.id') ?? ''),
                'name' => (string) (data_get($row, 'assetGroup.name') ?? ''),
                'status' => (string) (data_get($row, 'assetGroup.status') ?? ''),
                'primary_status' => (string) (data_get($row, 'assetGroup.primaryStatus') ?? ''),
            ])
            ->filter(static fn (array $group): bool => $group['id'] !== '')
            ->values()
            ->all();
    }

    /**
     * searchStream answers in chunks, each carrying its own results array.
     *
     * Flattening it is written out at every call site in this class; these
     * reads ask three times, so it is one method here instead.
     *
     * @return list<array<string, mixed>>
     */
    private function searchRows(GoogleAdsConnection $connection, string $query): array
    {
        $response = $this->search($connection, $query, fresh: true);
        if (! array_is_list($response)) {
            throw new RuntimeException('Google returned an incomplete search-stream response.');
        }
        $rows = [];
        foreach ($response as $chunk) {
            if (! is_array($chunk) || ! is_array($chunk['results'] ?? []) || ! array_is_list($chunk['results'] ?? [])) {
                throw new RuntimeException('Google returned malformed search results.');
            }
            foreach ($chunk['results'] ?? [] as $row) {
                if (! is_array($row)) {
                    throw new RuntimeException('Google returned a malformed search row.');
                }
                $rows[] = $row;
            }
        }

        return $rows;
    }

    /** @return array{selection: array<string, mixed>, available: list<string>} */
    public function readManagerGoals(GoogleAdsConnection $connection, string $campaignId): array
    {
        if (! ctype_digit($campaignId)) {
            throw new RuntimeException('Google campaign id must be numeric.');
        }
        $customer = $this->customerId($connection);
        $campaign = "customers/{$customer}/campaigns/{$campaignId}";
        $configs = $this->searchRows($connection, 'SELECT conversion_goal_campaign_config.campaign, conversion_goal_campaign_config.goal_config_level, conversion_goal_campaign_config.custom_conversion_goal FROM conversion_goal_campaign_config WHERE campaign.id = '.$campaignId);
        $config = count($configs) === 1 ? ($configs[0]['conversionGoalCampaignConfig'] ?? []) : [];
        if (($config['campaign'] ?? null) !== $campaign || ! in_array($config['goalConfigLevel'] ?? null, ['CUSTOMER', 'CAMPAIGN'], true)) {
            throw new RuntimeException('Google did not report complete conversion-goal configuration.');
        }
        $selection = ['level' => $config['goalConfigLevel']];
        $available = [];
        $selected = [];
        foreach ($this->searchRows($connection, 'SELECT campaign_conversion_goal.campaign, campaign_conversion_goal.category, campaign_conversion_goal.origin, campaign_conversion_goal.biddable FROM campaign_conversion_goal WHERE campaign.id = '.$campaignId) as $row) {
            $goal = $row['campaignConversionGoal'] ?? [];
            if (($goal['campaign'] ?? null) !== $campaign || ! preg_match('/^[A-Z_]+$/D', $goal['category'] ?? '') || ! preg_match('/^[A-Z_]+$/D', $goal['origin'] ?? '')
                || ! is_bool($goal['biddable'] ?? false)) {
                throw new RuntimeException('Google returned incomplete or unrelated conversion goals.');
            }
            $key = $goal['category'].'~'.$goal['origin'];
            if (in_array($key, $available, true)) {
                throw new RuntimeException('Google returned duplicate conversion goals.');
            }
            $available[] = $key;
            if ($goal['biddable'] ?? false) {
                $selected[] = ['category' => $goal['category'], 'origin' => $goal['origin']];
            }
        }
        if ($selection['level'] === 'CAMPAIGN') {
            $selection['goals'] = $selected;
            if (filled($config['customConversionGoal'] ?? null)) {
                if (! is_string($config['customConversionGoal']) || ! preg_match('/^customers\/'.$customer.'\/customConversionGoals\/[0-9]+$/D', $config['customConversionGoal'])) {
                    throw new RuntimeException('Google returned a foreign or malformed custom conversion goal.');
                }
                $selection['custom_goal'] = $config['customConversionGoal'];
            }
        }
        sort($available);

        return ['selection' => AdvancedEditFields::normalize('conversion_goals', $selection), 'available' => $available];
    }

    /** @param array<string, mixed> $desired
     * @param  array<string, mixed>  $expected
     */
    public function updateManagerGoals(GoogleAdsConnection $connection, string $campaignId, array $desired, array $expected): void
    {
        $current = $this->readManagerGoals($connection, $campaignId);
        if (Canonical::sort($current['selection']) !== Canonical::sort($expected)) {
            throw new RuntimeException('Google conversion goals changed after review. Nothing was sent.');
        }
        $customer = $this->customerId($connection);
        if (! in_array($desired['level'] ?? null, ['CUSTOMER', 'CAMPAIGN'], true)) {
            throw new RuntimeException('Choose account or campaign conversion goals.');
        }
        $selected = [];
        foreach ($desired['goals'] ?? [] as $goal) {
            $key = ($goal['category'] ?? '').'~'.($goal['origin'] ?? '');
            if (! in_array($key, $current['available'], true) || in_array($key, $selected, true)) {
                throw new RuntimeException('Choose distinct conversion goals from this campaign.');
            }
            $selected[] = $key;
        }
        if (isset($desired['custom_goal'])) {
            $resource = $desired['custom_goal'];
            if (! is_string($resource) || ! preg_match('/^customers\/'.$customer.'\/customConversionGoals\/([0-9]+)$/D', $resource, $match)) {
                throw new RuntimeException('Choose a custom conversion goal in this account.');
            }
            $rows = $this->searchRows($connection, 'SELECT custom_conversion_goal.resource_name, custom_conversion_goal.status FROM custom_conversion_goal WHERE custom_conversion_goal.id = '.$match[1]);
            if (count($rows) !== 1 || data_get($rows, '0.customConversionGoal.resourceName') !== $resource || data_get($rows, '0.customConversionGoal.status') !== 'ENABLED') {
                throw new RuntimeException('The custom conversion goal is not confirmed enabled in this account.');
            }
        }
        if ($desired['level'] === 'CAMPAIGN') {
            $operations = [];
            foreach ($current['available'] as $key) {
                $operations[] = ['update' => ['resourceName' => "customers/{$customer}/campaignConversionGoals/{$campaignId}~{$key}", 'biddable' => in_array($key, $selected, true)], 'updateMask' => 'biddable'];
            }
            if ($operations !== []) {
                $this->mutateMany($connection, 'campaignConversionGoals', $operations);
            }
        } elseif (count($desired) !== 1) {
            throw new RuntimeException('Account goals must not include campaign overrides.');
        }
        $this->mutateMany($connection, 'conversionGoalCampaignConfigs', [['update' => [
            'resourceName' => "customers/{$customer}/conversionGoalCampaignConfigs/{$campaignId}",
            'goalConfigLevel' => $desired['level'],
            ...($desired['level'] === 'CAMPAIGN' ? ['customConversionGoal' => $desired['custom_goal'] ?? ''] : []),
        ], 'updateMask' => $desired['level'] === 'CAMPAIGN' ? 'goal_config_level,custom_conversion_goal' : 'goal_config_level']]);
    }

    /**
     * Reconstruct supported native campaigns with a separate budget. Shared
     * assets/sets are referenced, never modified. The new parent stays paused.
     */
    public function duplicateManagerCampaign(GoogleAdsConnection $connection, string $campaignId): string
    {
        if (! ctype_digit($campaignId)) {
            throw new RuntimeException('Google campaign id must be numeric.');
        }
        $customer = $this->customerId($connection);
        $fields = [
            'resource_name', 'name', 'advertising_channel_type', 'advertising_channel_sub_type', 'status', 'campaign_budget',
            'bidding_strategy', 'bidding_strategy_type', 'manual_cpc.enhanced_cpc_enabled',
            'target_spend.cpc_bid_ceiling_micros', 'maximize_conversions.target_cpa_micros',
            'maximize_conversion_value.target_roas',
            'target_cpa.target_cpa_micros', 'target_cpa.cpc_bid_ceiling_micros', 'target_cpa.cpc_bid_floor_micros',
            'target_roas.target_roas', 'target_roas.cpc_bid_ceiling_micros', 'target_roas.cpc_bid_floor_micros',
            'network_settings.target_google_search', 'network_settings.target_search_network', 'network_settings.target_content_network', 'network_settings.target_partner_search_network',
            'geo_target_type_setting.positive_geo_target_type', 'geo_target_type_setting.negative_geo_target_type',
            'frequency_caps', 'tracking_url_template', 'final_url_suffix', 'url_custom_parameters', 'start_date_time', 'end_date_time',
            'contains_eu_political_advertising', 'brand_guidelines_enabled', 'asset_automation_settings',
            'brand_guidelines.accent_color', 'brand_guidelines.main_color', 'brand_guidelines.predefined_font_family',
            'text_guidelines.messaging_restrictions', 'text_guidelines.term_exclusions',
            'excluded_parent_asset_field_types', 'excluded_parent_asset_set_types', 'keyword_match_type',
            'real_time_bidding_setting.opt_in', 'audience_setting.use_audience_grouped', 'experiment_type', 'ai_max_setting.enable_ai_max',
            'pmax_campaign_settings.local_services_enabled', 'pmax_campaign_settings.brand_targeting_overrides.ignore_exclusions_for_shopping_ads',
            'vanity_pharma.vanity_pharma_display_url_mode', 'vanity_pharma.vanity_pharma_text',
            'third_party_integration_partners.brand_lift_integration_partners', 'third_party_integration_partners.brand_safety_integration_partners',
            'third_party_integration_partners.conversion_attribution_integration_partners', 'third_party_integration_partners.reach_integration_partners',
            'third_party_integration_partners.viewability_integration_partners',
            'ad_serving_optimization_status', 'payment_mode', 'optimization_goal_setting.optimization_goal_types',
            'targeting_setting.target_restrictions', 'selective_optimization.conversion_actions',
            'shopping_setting.merchant_id', 'dynamic_search_ads_setting.domain_name',
        ];
        $select = implode(', ', array_map(fn (string $field): string => 'campaign.'.$field, $fields));
        $rows = $this->searchRows($connection, "SELECT {$select}, customer.time_zone FROM campaign WHERE campaign.id = {$campaignId}");
        $source = count($rows) === 1 ? ($rows[0]['campaign'] ?? []) : [];
        $sourceResource = "customers/{$customer}/campaigns/{$campaignId}";
        if (($source['resourceName'] ?? null) !== $sourceResource || ! in_array($source['advertisingChannelType'] ?? null, ['SEARCH', 'DISPLAY', 'PERFORMANCE_MAX'], true)
            || ! in_array($source['advertisingChannelSubType'] ?? 'UNSPECIFIED', ['UNSPECIFIED'], true)
            || ! in_array($source['status'] ?? null, ['ENABLED', 'PAUSED'], true)) {
            throw new RuntimeException('Only readable standard Search, Display and non-retail Performance Max campaigns can be reconstructed here. No copy was created.');
        }
        if (filled($source['biddingStrategy'] ?? null)) {
            throw new RuntimeException('Portfolio bidding is shared. Detach or copy the campaign in Google Ads instead.');
        }
        if (filled(data_get($source, 'shoppingSetting.merchantId')) || filled(data_get($source, 'dynamicSearchAdsSetting.domainName'))) {
            throw new RuntimeException('Shopping feeds and dynamic-search campaigns need native specialized reconstruction. Nothing was copied.');
        }
        if (($source['experimentType'] ?? 'BASE') !== 'BASE' || data_get($source, 'aiMaxSetting.enableAiMax') === true
            || data_get($source, 'pmaxCampaignSettings.localServicesEnabled') === true) {
            throw new RuntimeException('Experiment, AI Max and Local Services configurations need specialized reconstruction. Nothing was copied.');
        }
        if (! in_array($source['adServingOptimizationStatus'] ?? 'UNSPECIFIED', ['UNSPECIFIED', 'OPTIMIZE'], true)) {
            throw new RuntimeException('Legacy campaign ad rotation cannot be recreated through the current Google API. Nothing was copied.');
        }
        $strategyBlock = match ($source['biddingStrategyType'] ?? null) {
            'MANUAL_CPC' => 'manualCpc', 'MANUAL_CPM' => 'manualCpm', 'TARGET_SPEND' => 'targetSpend',
            'MAXIMIZE_CONVERSIONS' => 'maximizeConversions', 'MAXIMIZE_CONVERSION_VALUE' => 'maximizeConversionValue',
            'TARGET_CPA' => 'targetCpa', 'TARGET_ROAS' => 'targetRoas',
            default => throw new RuntimeException('This bidding strategy cannot be reconstructed without losing settings. Nothing was copied.'),
        };
        $budgetResource = (string) ($source['campaignBudget'] ?? '');
        if (! preg_match('/^customers\/'.$customer.'\/campaignBudgets\/([0-9]+)$/D', $budgetResource, $match)) {
            throw new RuntimeException('Google did not report this campaign budget.');
        }
        $budgets = $this->searchRows($connection, 'SELECT campaign_budget.resource_name, campaign_budget.amount_micros, campaign_budget.total_amount_micros, campaign_budget.delivery_method, campaign_budget.period FROM campaign_budget WHERE campaign_budget.id = '.$match[1]);
        $budget = count($budgets) === 1 ? ($budgets[0]['campaignBudget'] ?? []) : [];
        if (($budget['resourceName'] ?? null) !== $budgetResource || ! is_numeric($budget['amountMicros'] ?? null) || (int) $budget['amountMicros'] <= 0
            || ! in_array($budget['period'] ?? null, ['DAILY'], true) || ! empty($budget['totalAmountMicros'])) {
            throw new RuntimeException('Only a confirmed daily budget can be safely reconstructed here.');
        }
        $goals = $this->readManagerGoals($connection, $campaignId);
        $criteria = $this->copyCriterionPayloads($connection, 'campaign', $campaignId);
        $assets = $this->copyLinkPayloads($connection, 'campaign_asset', $campaignId, ['asset', 'field_type', 'status']);
        $sets = $this->copyLinkPayloads($connection, 'campaign_shared_set', $campaignId, ['shared_set', 'status']);
        $assetSets = $this->copyLinkPayloads($connection, 'campaign_asset_set', $campaignId, ['asset_set', 'status']);
        $this->assertCopyRelationsSupported($connection, 'campaign', $campaignId);
        $structure = $this->readCampaignStructure($connection, $campaignId);
        if (count($structure['ad_groups']) > 100) {
            throw new RuntimeException('Too many ad groups to reconstruct and verify safely in one operation.');
        }
        foreach ($structure['ad_groups'] as $group) {
            $this->copyableAdCount($connection, (string) $group['id']);
            $this->copyCriterionPayloads($connection, 'ad_group', (string) $group['id'], $source['biddingStrategyType']);
            $this->copyAdGroupModifierPlan($connection, (string) $group['id']);
            $this->assertCopyRelationsSupported($connection, 'ad_group', (string) $group['id']);
            $this->copyLinkPayloads($connection, 'ad_group_asset', (string) $group['id'], ['asset', 'field_type', 'status'], 'ad_group');
            $this->copyLinkPayloads($connection, 'ad_group_asset_set', (string) $group['id'], ['asset_set', 'status'], 'ad_group');
        }
        $assetGroups = [];
        if ($source['advertisingChannelType'] === 'PERFORMANCE_MAX') {
            $assetGroups = $this->copyAssetGroupPlan($connection, $campaignId);
        }
        $zone = data_get($rows, '0.customer.timeZone');
        if (! is_string($zone) || ! in_array($zone, timezone_identifiers_list(), true)) {
            throw new RuntimeException('Google did not report the account time zone.');
        }
        $now = CarbonImmutable::now($zone);
        if (filled($source['endDateTime'] ?? null) && CarbonImmutable::parse($source['endDateTime'], $zone)->lte($now)) {
            throw new RuntimeException('An expired campaign end cannot be preserved on a new copy.');
        }
        $payload = array_diff_key($source, array_flip(['id', 'resourceName', 'status', 'campaignBudget', 'biddingStrategyType', 'biddingStrategy', 'shoppingSetting', 'dynamicSearchAdsSetting', 'experimentType', 'adServingOptimizationStatus']));
        if ($source['advertisingChannelType'] !== 'PERFORMANCE_MAX') {
            if (($source['brandGuidelinesEnabled'] ?? false) !== false || filled($source['brandGuidelines'] ?? null)) {
                throw new RuntimeException('Google reported Performance Max brand settings on an incompatible campaign.');
            }
            unset($payload['brandGuidelinesEnabled'], $payload['brandGuidelines']);
        }
        $payload[$strategyBlock] = ! empty($source[$strategyBlock]) ? $source[$strategyBlock] : (object) [];
        $payload['name'] = mb_substr((string) $source['name'], 0, 100).' - copy '.Str::lower(Str::random(8));
        $payload['status'] = 'PAUSED';
        $payload['startDateTime'] = max($source['startDateTime'] ?? '', $now->addMinute()->format('Y-m-d H:i:s'));
        if (filled($source['endDateTime'] ?? null) && $source['endDateTime'] <= $payload['startDateTime']) {
            throw new RuntimeException('The remaining campaign schedule ends before a safe new start. Nothing was copied.');
        }
        if (($payload['advertisingChannelSubType'] ?? null) === 'UNSPECIFIED') {
            unset($payload['advertisingChannelSubType']);
        }
        $payload = $this->copyMessageContainers($payload);
        $createdBudget = null;
        $createdCampaign = null;
        try {
            $budgetResource = $this->firstResourceName($this->mutate($connection, 'campaignBudgets', ['create' => [
                ...array_intersect_key($budget, array_flip(['amountMicros', 'deliveryMethod', 'period'])),
                'name' => $payload['name'].' budget', 'explicitlyShared' => false,
            ]]), 'campaignBudgetResult');
            if (! is_string($budgetResource) || ! preg_match('/^customers\/'.$customer.'\/campaignBudgets\/[0-9]+$/D', $budgetResource)
                || $budgetResource === $source['campaignBudget']) {
                throw new RuntimeException('Google did not return the copied budget ID. Inspect the account before retrying.');
            }
            $createdBudget = $budgetResource;
            $payload['campaignBudget'] = $createdBudget;
            $campaignResource = $this->firstResourceName($this->mutate($connection, 'campaigns', ['create' => $payload]), 'campaignResult');
            if (! is_string($campaignResource) || ! preg_match('/^customers\/'.$customer.'\/campaigns\/[0-9]+$/D', $campaignResource)
                || $campaignResource === $sourceResource) {
                throw new RuntimeException('Google did not return the copied campaign ID. Inspect the account before retrying.');
            }
            $createdCampaign = $campaignResource;
            $copyId = $this->resourceId($createdCampaign);
            foreach ([['campaignCriteria', $criteria], ['campaignAssets', $assets], ['campaignSharedSets', $sets], ['campaignAssetSets', $assetSets]] as [$collection, $objects]) {
                if ($objects !== []) {
                    $operations = [];
                    $devices = $collection === 'campaignCriteria'
                        ? $this->searchRows($connection, "SELECT campaign_criterion.resource_name, campaign_criterion.device.type FROM campaign_criterion WHERE campaign.id = {$copyId} AND campaign_criterion.type = 'DEVICE' AND campaign_criterion.status != 'REMOVED'") : [];
                    foreach ($objects as $object) {
                        if ($collection === 'campaignCriteria' && isset($object['device'])) {
                            if (! array_key_exists('bidModifier', $object)) {
                                continue;
                            }
                            $targetDevice = collect($devices)->firstWhere('campaignCriterion.device.type', $object['device']['type']);
                            $targetResource = data_get($targetDevice, 'campaignCriterion.resourceName');
                            if (! is_string($targetResource) || ! str_starts_with($targetResource, "customers/{$customer}/campaignCriteria/{$copyId}~")
                                || ! is_numeric($object['bidModifier'] ?? null)) {
                                throw new RuntimeException('Google did not report an owned target device criterion and source bid modifier.');
                            }
                            $operations[] = ['update' => ['resourceName' => $targetResource, 'bidModifier' => $object['bidModifier']], 'updateMask' => 'bid_modifier'];
                        } else {
                            $operations[] = ['create' => [...$object, 'campaign' => $createdCampaign]];
                        }
                    }
                    if ($operations !== []) {
                        $this->mutateMany($connection, $collection, $operations, ['partialFailure' => false]);
                    }
                }
            }
            $copyGoals = $this->readManagerGoals($connection, $copyId);
            $this->updateManagerGoals($connection, $copyId, $goals['selection'], $copyGoals['selection']);
            foreach ($structure['ad_groups'] as $group) {
                $this->duplicateAdGroup($connection, (string) $group['id'], withAds: true, targetCampaign: $createdCampaign, expectedCampaignId: $campaignId);
            }
            foreach ($assetGroups as $plan) {
                $this->createCopiedAssetGroup($connection, $createdCampaign, $plan);
            }
            $profile = $this->readCampaignProfile($connection, $copyId, fresh: true);
            if ($profile['status'] !== 'PAUSED' || $profile['name'] !== $payload['name'] || $profile['budget_resource'] !== $createdBudget
                || $this->readManagerGoals($connection, $copyId)['selection'] !== $goals['selection']) {
                throw new RuntimeException('Google did not confirm the paused campaign copy, independent budget or conversion goals.');
            }
            $copiedStructure = $this->readCampaignStructure($connection, $copyId);
            foreach (['ad_groups', 'ads', 'asset_groups'] as $children) {
                if (count($structure[$children]) !== count($copiedStructure[$children])
                    || array_filter($copiedStructure[$children], fn (array $child): bool => ($child['status'] ?? null) !== 'PAUSED') !== []) {
                    throw new RuntimeException('Google did not confirm the complete copied child count and PAUSED states.');
                }
            }
            $readback = $this->searchRows($connection, "SELECT {$select}, customer.time_zone FROM campaign WHERE campaign.id = {$copyId}");
            $this->assertCopiedFields($readback[0]['campaign'] ?? [], $payload);
            $budgetReadback = $this->searchRows($connection, 'SELECT campaign_budget.resource_name, campaign_budget.amount_micros, campaign_budget.delivery_method, campaign_budget.period, campaign_budget.explicitly_shared, campaign_budget.reference_count FROM campaign_budget WHERE campaign_budget.id = '.$this->resourceId($createdBudget));
            $this->assertCopiedFields($budgetReadback[0]['campaignBudget'] ?? [], [
                ...array_intersect_key($budget, array_flip(['amountMicros', 'deliveryMethod', 'period'])),
                'resourceName' => $createdBudget, 'explicitlyShared' => false,
            ]);
            if ((int) data_get($budgetReadback, '0.campaignBudget.referenceCount', 0) !== 1) {
                throw new RuntimeException('Google did not confirm an independent budget for the copied campaign.');
            }
            foreach ([[$criteria, $this->copyCriterionPayloads($connection, 'campaign', $copyId)],
                [$assets, $this->copyLinkPayloads($connection, 'campaign_asset', $copyId, ['asset', 'field_type', 'status'])],
                [$sets, $this->copyLinkPayloads($connection, 'campaign_shared_set', $copyId, ['shared_set', 'status'])],
                [$assetSets, $this->copyLinkPayloads($connection, 'campaign_asset_set', $copyId, ['asset_set', 'status'])]] as [$expected, $actual]) {
                if ($this->copySet($actual) !== $this->copySet($expected)) {
                    throw new RuntimeException('Google did not confirm the copied criteria or shared asset links.');
                }
            }

            return $copyId;
        } catch (Throwable $exception) {
            $left = [];
            foreach (array_filter(['campaigns' => $createdCampaign, 'campaignBudgets' => $createdBudget]) as $collection => $resource) {
                try {
                    $this->removeResource($connection, $resource, $collection);
                } catch (Throwable $cleanup) {
                    report($cleanup);
                    $left[] = $resource;
                }
            }
            throw new RuntimeException($exception->getMessage().($left === [] ? ' Incomplete copies were removed.' : ' Cleanup is incomplete; PAUSED resources remain: '.implode(', ', $left)), 0, $exception);
        }
    }

    /** @return list<array<string, mixed>> */
    private function copyCriterionPayloads(GoogleAdsConnection $connection, string $scope, string $id, ?string $strategy = null): array
    {
        $resource = $scope.'_criterion';
        $customer = $this->customerId($connection);
        $resourceKey = $scope === 'campaign' ? 'campaignCriterion' : 'adGroupCriterion';
        $types = $this->searchRows($connection, "SELECT {$resource}.type FROM {$resource} WHERE {$scope}.id = {$id} AND {$resource}.status != 'REMOVED'");
        $payloads = [];
        foreach (array_unique(array_map(fn (array $row): string => (string) data_get($row, $resourceKey.'.type'), $types)) as $type) {
            if (! isset(self::COPY_CRITERIA[$type]) || ($scope === 'ad_group' && in_array($type, ['DEVICE', 'AD_SCHEDULE', 'CONTENT_LABEL', 'IP_BLOCK', 'PROXIMITY'], true))) {
                throw new RuntimeException("The {$scope} contains unsupported {$type} criteria; lossless reconstruction is unavailable.");
            }
            [$block, $leaves] = self::COPY_CRITERIA[$type];
            $select = implode(', ', array_map(fn (string $leaf): string => "{$resource}.{$block}.{$leaf}", $leaves));
            if ($scope === 'ad_group') {
                $select .= ', '.implode(', ', array_map(fn (string $field): string => "{$resource}.{$field}", [
                    'cpc_bid_micros', 'cpm_bid_micros', 'cpv_bid_micros', 'percent_cpc_bid_micros',
                    'final_urls', 'final_mobile_urls', 'tracking_url_template', 'final_url_suffix', 'url_custom_parameters',
                ]));
            }
            $rows = $this->searchRows($connection, "SELECT {$resource}.resource_name, {$resource}.status, {$resource}.negative, {$resource}.bid_modifier, {$select} FROM {$resource} WHERE {$scope}.id = {$id} AND {$resource}.type = '{$type}' AND {$resource}.status != 'REMOVED'");
            $camel = Str::camel($block);
            $prefix = 'customers/'.$customer.'/'.($scope === 'campaign' ? 'campaignCriteria' : 'adGroupCriteria').'/'.$id.'~';
            foreach ($rows as $row) {
                $criterion = $row[$resourceKey] ?? [];
                if (! str_starts_with($criterion['resourceName'] ?? '', $prefix) || ! is_array($criterion[$camel] ?? null)
                    || ! in_array($criterion['status'] ?? null, ['ENABLED', 'PAUSED'], true)) {
                    throw new RuntimeException('Google returned incomplete or foreign copy criteria.');
                }
                $payload = array_intersect_key($criterion, array_flip([$camel, 'status', 'negative', 'bidModifier']));
                if ($scope === 'ad_group') {
                    if (! empty($criterion['percentCpcBidMicros'])) {
                        throw new RuntimeException('Percentage CPC criterion bidding requires specialized reconstruction.');
                    }
                    $payload = [...$payload, ...$this->copyBidOverrides($criterion, $strategy)];
                    foreach (['finalUrls', 'finalMobileUrls', 'trackingUrlTemplate', 'finalUrlSuffix', 'urlCustomParameters'] as $field) {
                        if (filled($criterion[$field] ?? null)) {
                            $payload[$field] = $criterion[$field];
                        }
                    }
                }
                $payloads[] = $payload;
            }
        }
        if (count($payloads) !== count($types)) {
            throw new RuntimeException('The source criteria changed during reconstruction. Nothing was copied.');
        }

        return $payloads;
    }

    /**
     * Zero-valued native bid defaults mean inheritance, not writable overrides.
     *
     * @param  array<string, mixed>  $source
     * @return array<string, mixed>
     */
    private function copyBidOverrides(array $source, ?string $strategy): array
    {
        $overrides = [];
        foreach ([
            'cpcBidMicros' => ['MANUAL_CPC'], 'cpmBidMicros' => ['MANUAL_CPM'], 'cpvBidMicros' => ['MANUAL_CPV'],
            'targetCpaMicros' => ['TARGET_CPA', 'MAXIMIZE_CONVERSIONS'],
            'targetRoas' => ['TARGET_ROAS', 'MAXIMIZE_CONVERSION_VALUE'],
        ] as $field => $strategies) {
            if (! isset($source[$field])) {
                continue;
            }
            if (! is_numeric($source[$field]) || ! is_finite((float) $source[$field]) || $source[$field] < 0) {
                throw new RuntimeException("Google returned an invalid {$field} override.");
            }
            if ($source[$field] > 0) {
                if ($strategy === null) {
                    throw new RuntimeException('Google did not report the bidding strategy needed to preserve bid overrides.');
                }
                if (in_array($strategy, $strategies, true)) {
                    $overrides[$field] = $source[$field];
                }
            }
        }

        return $overrides;
    }

    /** @param list<string> $fields
     * @return list<array<string, mixed>>
     */
    private function copyLinkPayloads(GoogleAdsConnection $connection, string $resource, string $id, array $fields, string $scope = 'campaign'): array
    {
        $parent = Str::camel($scope);
        $select = implode(', ', [$scope.'.id', ...array_map(fn (string $field): string => $resource.'.'.$field, [$scope, ...$fields])]);
        $key = Str::camel($resource);
        $expected = 'customers/'.$this->customerId($connection).'/'.($scope === 'campaign' ? 'campaigns' : 'adGroups').'/'.$id;
        $payloads = [];
        foreach ($this->searchRows($connection, "SELECT {$select} FROM {$resource} WHERE {$scope}.id = {$id} AND {$resource}.status != 'REMOVED'") as $row) {
            $link = $row[$key] ?? [];
            $target = str_ends_with($resource, '_asset_set') ? 'assetSet' : (str_ends_with($resource, '_shared_set') ? 'sharedSet' : 'asset');
            $collection = match ($target) {
                'assetSet' => 'assetSets', 'sharedSet' => 'sharedSets', default => 'assets',
            };
            if (($link[$parent] ?? null) !== $expected
                || ! preg_match('/^customers\/'.$this->customerId($connection).'\/'.$collection.'\/[0-9]+$/D', $link[$target] ?? '')
                || ! in_array($link['status'] ?? null, ['ENABLED', 'PAUSED'], true)
                || ($target === 'asset' && ! filled($link['fieldType'] ?? null))) {
                throw new RuntimeException('Google returned a foreign campaign link.');
            }
            $payloads[] = array_intersect_key($link, array_flip(array_map(Str::camel(...), $fields)));
        }

        return $payloads;
    }

    private function assertCopyRelationsSupported(GoogleAdsConnection $connection, string $scope, string $id): void
    {
        $relations = [$scope.'_customizer'];
        foreach ($relations as $resource) {
            if ($this->searchRows($connection, "SELECT {$scope}.id, {$resource}.resource_name FROM {$resource} WHERE {$scope}.id = {$id}") !== []) {
                throw new RuntimeException('Native customizer values need specialized reconstruction. No settings were silently dropped.');
            }
        }
    }

    /**
     * An unset optional modifier inherits; it is not a zero multiplier.
     *
     * @return list<array{resourceName: string, device: array{type: string}, bidModifier: ?float}>
     */
    private function copyAdGroupModifierPlan(GoogleAdsConnection $connection, string $id): array
    {
        $modifiers = [];
        $prefix = 'customers/'.$this->customerId($connection).'/adGroupBidModifiers/'.$id.'~';
        foreach ($this->searchRows($connection, "SELECT ad_group.id, ad_group_bid_modifier.resource_name, ad_group_bid_modifier.bid_modifier, ad_group_bid_modifier.device.type FROM ad_group_bid_modifier WHERE ad_group.id = {$id}") as $row) {
            $modifier = $row['adGroupBidModifier'] ?? [];
            $device = data_get($modifier, 'device.type');
            $bid = $modifier['bidModifier'] ?? null;
            if (! str_starts_with($modifier['resourceName'] ?? '', $prefix)
                || ! in_array($device, ['DESKTOP', 'MOBILE', 'TABLET', 'CONNECTED_TV'], true)
                || ($bid !== null && (! is_numeric($bid) || $bid < 0 || $bid > 10))
                || isset($modifiers[$device])) {
                throw new RuntimeException('Google returned incomplete, duplicate, foreign or non-device bid modifiers.');
            }
            $modifiers[$device] = ['resourceName' => $modifier['resourceName'], 'device' => ['type' => $device], 'bidModifier' => $bid !== null ? (float) $bid : null];
        }

        return array_values($modifiers);
    }

    /** @return list<array<string, mixed>> */
    private function copyAssetGroupPlan(GoogleAdsConnection $connection, string $campaignId): array
    {
        $plans = [];
        foreach ($this->searchRows($connection, "SELECT campaign.id, asset_group.resource_name, asset_group.campaign, asset_group.name, asset_group.status, asset_group.final_urls, asset_group.final_mobile_urls, asset_group.path1, asset_group.path2 FROM asset_group WHERE campaign.id = {$campaignId} AND asset_group.status != 'REMOVED'") as $row) {
            $group = $row['assetGroup'] ?? [];
            $prefix = 'customers/'.$this->customerId($connection).'/';
            if (($group['campaign'] ?? null) !== $prefix.'campaigns/'.$campaignId
                || ! is_string($group['name'] ?? null) || trim($group['name']) === ''
                || ! in_array($group['status'] ?? null, ['ENABLED', 'PAUSED'], true)
                || ! is_array($group['finalUrls'] ?? null) || $group['finalUrls'] === []
                || ! preg_match('/^'.preg_quote($prefix, '/').'assetGroups\/([0-9]+)$/D', $group['resourceName'] ?? '', $match)) {
                throw new RuntimeException('Google returned a foreign asset group.');
            }
            $id = $match[1];
            $filters = $this->searchRows($connection, "SELECT asset_group.id, asset_group_listing_group_filter.resource_name FROM asset_group_listing_group_filter WHERE asset_group.id = {$id}");
            if ($filters !== []) {
                throw new RuntimeException('Retail/listing-group Performance Max copies require Google Ads. No lossy copy was created.');
            }
            $links = $this->searchRows($connection, "SELECT asset_group.id, asset_group_asset.asset_group, asset_group_asset.asset, asset_group_asset.field_type, asset_group_asset.status FROM asset_group_asset WHERE asset_group.id = {$id} AND asset_group_asset.status != 'REMOVED'");
            $signals = $this->searchRows($connection, "SELECT asset_group.id, asset_group_signal.asset_group, asset_group_signal.audience.audience, asset_group_signal.search_theme.text FROM asset_group_signal WHERE asset_group.id = {$id}");
            $assetPayloads = [];
            foreach ($links as $row) {
                $link = $row['assetGroupAsset'] ?? [];
                if (($link['assetGroup'] ?? null) !== $group['resourceName']
                    || ! preg_match('/^'.preg_quote($prefix, '/').'assets\/[0-9]+$/D', $link['asset'] ?? '')
                    || ! filled($link['fieldType'] ?? null) || ! in_array($link['status'] ?? null, ['ENABLED', 'PAUSED'], true)) {
                    throw new RuntimeException('Google returned incomplete or foreign asset group asset links.');
                }
                $assetPayloads[] = $link;
            }
            $signalPayloads = [];
            foreach ($signals as $row) {
                $signal = $row['assetGroupSignal'] ?? [];
                $audience = data_get($signal, 'audience.audience');
                $theme = data_get($signal, 'searchTheme.text');
                if (($signal['assetGroup'] ?? null) !== $group['resourceName'] || ($audience === null) === ($theme === null)
                    || ($audience !== null && (! is_string($audience) || ! preg_match('/^'.preg_quote($prefix, '/').'audiences\/[0-9]+$/D', $audience)))
                    || ($theme !== null && (! is_string($theme) || trim($theme) === ''))) {
                    throw new RuntimeException('Google returned incomplete or foreign asset group signals.');
                }
                $signalPayloads[] = $signal;
            }
            $plans[] = ['group' => $group, 'assets' => $assetPayloads, 'signals' => $signalPayloads];
        }

        return $plans;
    }

    public function duplicateManagerAssetGroup(GoogleAdsConnection $connection, string $campaignId, string $assetGroupId): string
    {
        if (! ctype_digit($campaignId) || ! ctype_digit($assetGroupId)) {
            throw new RuntimeException('Choose numeric Google campaign and asset group IDs.');
        }
        $plan = collect($this->copyAssetGroupPlan($connection, $campaignId))->first(
            fn (array $candidate): bool => $this->resourceId($candidate['group']['resourceName']) === $assetGroupId,
        );
        if ($plan === null) {
            throw new RuntimeException('This asset group is not part of the selected campaign.');
        }
        $plan['group']['name'] = mb_substr($plan['group']['name'], 0, 100).' - copy '.Str::lower(Str::random(8));

        return $this->resourceId($this->createCopiedAssetGroup($connection, 'customers/'.$this->customerId($connection).'/campaigns/'.$campaignId, $plan));
    }

    /** @param array<string, mixed> $plan */
    private function createCopiedAssetGroup(GoogleAdsConnection $connection, string $campaign, array $plan): string
    {
        $group = array_intersect_key($plan['group'], array_flip(['name', 'finalUrls', 'finalMobileUrls', 'path1', 'path2']));
        $temporary = 'customers/'.$this->customerId($connection).'/assetGroups/-1';
        $operations = [['assetGroupOperation' => ['create' => [...$group, 'resourceName' => $temporary, 'campaign' => $campaign, 'status' => 'PAUSED']]]];
        foreach (['assetGroupAssetOperation' => $plan['assets'], 'assetGroupSignalOperation' => $plan['signals']] as $operation => $links) {
            foreach ($links as $link) {
                if (($link['assetGroup'] ?? null) !== $plan['group']['resourceName']) {
                    throw new RuntimeException('Google returned a foreign asset group asset or signal.');
                }
                $operations[] = [$operation => ['create' => [
                    ...array_diff_key($link, ['resourceName' => true, 'assetGroup' => true]), 'assetGroup' => $temporary,
                ]]];
            }
        }
        $response = $this->mutateMany($connection, 'googleAds', $operations, ['partialFailure' => false]);
        $resource = data_get($response, 'mutateOperationResponses.0.assetGroupResult.resourceName');
        if (! is_string($resource) || ! preg_match('/^customers\/'.$this->customerId($connection).'\/assetGroups\/[0-9]+$/D', $resource)
            || $resource === $plan['group']['resourceName']) {
            throw new RuntimeException('Google did not return the copied asset group ID.');
        }
        try {
            $plans = $this->copyAssetGroupPlan($connection, $this->resourceId($campaign));
            $actual = collect($plans)->first(fn (array $candidate): bool => $candidate['group']['resourceName'] === $resource);
            if ($actual === null || ($actual['group']['status'] ?? null) !== 'PAUSED') {
                throw new RuntimeException('Google did not confirm the copied asset group as PAUSED.');
            }
            $this->assertCopiedFields($actual['group'], $group);
            foreach (['assets', 'signals'] as $links) {
                $withoutParent = fn (array $link): array => array_diff_key($link, ['assetGroup' => true]);
                if ($this->copySet(array_map($withoutParent, $actual[$links])) !== $this->copySet(array_map($withoutParent, $plan[$links]))) {
                    throw new RuntimeException('Google did not confirm all copied asset group assets and signals.');
                }
            }
        } catch (Throwable $exception) {
            try {
                $this->removeResource($connection, $resource, 'assetGroups');
            } catch (Throwable $cleanup) {
                report($cleanup);
                throw new RuntimeException($exception->getMessage().' Cleanup is incomplete; PAUSED asset group remains: '.$resource, 0, $exception);
            }
            throw new RuntimeException($exception->getMessage().' Incomplete asset group copy was removed.', 0, $exception);
        }

        return $resource;
    }

    /**
     * Associative JSON decoding loses the distinction between {} and [].
     *
     * @param  array<mixed>  $payload
     * @return array<mixed>
     */
    private function copyMessageContainers(array $payload): array
    {
        $messages = [
            'networkSettings', 'geoTargetTypeSetting', 'brandGuidelines', 'textGuidelines', 'realTimeBiddingSetting',
            'audienceSetting', 'targetingSetting', 'selectiveOptimization', 'optimizationGoalSetting',
            'thirdPartyIntegrationPartners', 'aiMaxSetting', 'pmaxCampaignSettings', 'brandTargetingOverrides',
            'localServicesPmaxCampaignSettings', 'vanityPharma', 'controlSpec', 'longHeadline', 'geoPoint', 'address',
        ];
        foreach ($payload as $key => $value) {
            if (is_array($value)) {
                $payload[$key] = $value === [] && in_array($key, $messages, true)
                    ? (object) [] : $this->copyMessageContainers($value);
            }
        }

        return $payload;
    }

    /** @param array<string, mixed> $actual
     * @param  array<string, mixed>  $expected
     */
    private function assertCopiedFields(array $actual, array $expected): void
    {
        foreach ($expected as $field => $value) {
            if ($field === 'advertisingChannelSubType' && $value === 'UNSPECIFIED') {
                continue;
            }
            $normalized = json_decode(json_encode($value, JSON_THROW_ON_ERROR), true, flags: JSON_THROW_ON_ERROR);
            $seen = $actual[$field] ?? match (true) {
                $normalized === [] => [],
                $normalized === false => false,
                $normalized === '' => '',
                default => null,
            };
            if (is_array($normalized) && ! array_is_list($normalized) && is_array($seen)) {
                $this->assertCopiedFields($seen, $normalized);
            } elseif ((is_array($normalized) ? (is_array($seen) ? Canonical::sort($seen) : null) : $seen) !== (is_array($normalized) ? Canonical::sort($normalized) : $normalized)) {
                throw new RuntimeException('Google did not confirm copied '.$field.'.');
            }
        }
    }

    /** @param list<array<string, mixed>> $rows
     * @return list<string>
     */
    private function copySet(array $rows): array
    {
        $values = array_map(fn (array $row): string => json_encode(Canonical::sort($row), JSON_THROW_ON_ERROR), $rows);
        sort($values);

        return $values;
    }

    /**
     * Read Search keyword and user-list criteria at their actual ad-group scope.
     * These are an imported baseline, not editable draft selections.
     *
     * @return list<array<string, string|bool>>
     */
    public function readCampaignSearchCriteria(GoogleAdsConnection $connection, string $googleCampaignId): array
    {
        if (! preg_match('/^[0-9]+$/D', $googleCampaignId)) {
            throw new RuntimeException('Google campaign id must be numeric.');
        }

        $customerId = $this->customerId($connection);
        $query = <<<GAQL
SELECT
  ad_group_criterion.resource_name,
  ad_group_criterion.ad_group,
  ad_group_criterion.type,
  ad_group_criterion.status,
  ad_group_criterion.negative,
  ad_group_criterion.keyword.text,
  ad_group_criterion.keyword.match_type,
  ad_group_criterion.user_list.user_list,
  ad_group.targeting_setting.target_restrictions
FROM ad_group_criterion
WHERE campaign.id = {$googleCampaignId}
  AND ad_group_criterion.type IN ('KEYWORD', 'USER_LIST')
  AND ad_group_criterion.status != 'REMOVED'
GAQL;

        return collect($this->search($connection, $query, fresh: true))
            ->flatMap(static fn (array $chunk): array => $chunk['results'] ?? [])
            ->map(static function (array $row) use ($customerId): array {
                $criterion = (array) ($row['adGroupCriterion'] ?? []);
                $type = (string) ($criterion['type'] ?? '');
                $resource = (string) ($criterion['resourceName'] ?? '');
                $adGroup = (string) ($criterion['adGroup'] ?? '');
                $status = (string) ($criterion['status'] ?? '');

                if (! in_array($type, ['KEYWORD', 'USER_LIST'], true)
                    || ! preg_match('/^customers\/'.$customerId.'\/adGroupCriteria\/([0-9]+)~[0-9]+$/D', $resource, $criterionMatch)
                    || $adGroup !== 'customers/'.$customerId.'/adGroups/'.$criterionMatch[1]
                    || ! in_array($status, ['ENABLED', 'PAUSED'], true)
                    || ! is_bool($criterion['negative'] ?? false)) {
                    throw new RuntimeException('Google returned an incomplete Search criterion; import was cancelled.');
                }

                $result = [
                    'criterion' => $resource,
                    'ad_group' => $adGroup,
                    'type' => $type,
                    'status' => $status,
                    'negative' => $criterion['negative'] ?? false,
                ];

                if ($type === 'KEYWORD') {
                    $keyword = (array) ($criterion['keyword'] ?? []);
                    $text = trim((string) ($keyword['text'] ?? ''));
                    $matchType = (string) ($keyword['matchType'] ?? '');

                    if ($text === '' || ! in_array($matchType, ['BROAD', 'PHRASE', 'EXACT'], true)) {
                        throw new RuntimeException('Google returned a keyword without text or match type; import was cancelled.');
                    }

                    return [...$result, 'text' => $text, 'match_type' => $matchType];
                }

                $userList = (string) data_get($criterion, 'userList.userList', '');

                if (! preg_match('/^customers\/'.$customerId.'\/userLists\/[0-9]+$/D', $userList)) {
                    throw new RuntimeException('Google returned an audience criterion without an account-owned list ID; import was cancelled.');
                }

                $restrictions = (array) data_get($row, 'adGroup.targetingSetting.targetRestrictions', []);
                $audience = collect($restrictions)->first(static fn (mixed $restriction): bool => is_array($restriction)
                    && ($restriction['targetingDimension'] ?? null) === 'AUDIENCE');

                return [
                    ...$result,
                    'user_list' => $userList,
                    'audience_bid_only' => $audience === null ? false : ($audience['bidOnly'] ?? false) === true,
                ];
            })
            ->sortBy('criterion')
            ->values()
            ->all();
    }

    public function readCampaignGeoPresence(GoogleAdsConnection $connection, string $googleCampaignId, bool $fresh = false): string
    {
        if (! preg_match('/^[0-9]+$/D', $googleCampaignId)) {
            throw new RuntimeException('Google campaign id must be numeric.');
        }

        $query = "SELECT campaign.geo_target_type_setting.positive_geo_target_type FROM campaign WHERE campaign.id = {$googleCampaignId}";
        $rows = collect($this->search($connection, $query, fresh: $fresh))
            ->flatMap(fn (mixed $chunk): array => is_array($chunk) ? ($chunk['results'] ?? []) : [])
            ->values();
        $mode = data_get($rows->first(), 'campaign.geoTargetTypeSetting.positiveGeoTargetType')
            ?? data_get($rows->first(), 'campaign.geo_target_type_setting.positive_geo_target_type');

        if ($rows->count() !== 1 || ! in_array($mode, ['PRESENCE', 'PRESENCE_OR_INTEREST'], true)) {
            throw new RuntimeException('Google returned an unavailable location-presence setting. Review the campaign before editing locations.');
        }

        return $mode;
    }

    /**
     * Location targets attached to a campaign. Does not mutate.
     *
     * @return list<string>
     */
    public function readCampaignGeoTargets(GoogleAdsConnection $connection, string $googleCampaignId): array
    {
        if (! preg_match('/^[0-9]+$/D', $googleCampaignId)) {
            throw new RuntimeException('Google campaign id must be numeric.');
        }

        $query = "SELECT campaign_criterion.location.geo_target_constant FROM campaign_criterion WHERE campaign.id = {$googleCampaignId} AND campaign_criterion.type = 'LOCATION' AND campaign_criterion.status != 'REMOVED'";
        $resources = collect($this->search($connection, $query))
            ->flatMap(fn (mixed $chunk): array => is_array($chunk) ? ($chunk['results'] ?? []) : [])
            ->map(fn (array $row): string => (string) (data_get($row, 'campaignCriterion.location.geoTargetConstant')
                ?? data_get($row, 'campaign_criterion.location.geo_target_constant') ?? ''))
            ->unique()
            ->values()
            ->all();
        $metadata = $this->geoTargetMetadata($connection, $resources);

        return collect($resources)
            ->map(fn (string $resource): string => (string) (data_get($metadata[$resource] ?? [], 'geoTargetConstant.canonicalName')
                ?? data_get($metadata[$resource] ?? [], 'geo_target_constant.canonical_name')
                ?? data_get($metadata[$resource] ?? [], 'geoTargetConstant.countryCode')
                ?? data_get($metadata[$resource] ?? [], 'geo_target_constant.country_code')
                ?? ''))
            ->filter()
            ->unique()
            ->values()
            ->all();
    }

    /**
     * Read the exact included and excluded location criteria for adoption.
     * Unknown geographic types remain explicit in the imported baseline.
     *
     * @return list<array{criterion: string, geo_target: string, country_code: string, target_type: string, name: string, negative: bool, status?: string}>
     */
    public function readCampaignLocationCriteria(GoogleAdsConnection $connection, string $googleCampaignId, bool $includeStatus = false, bool $allowProximity = false, bool $fresh = false): array
    {
        if (! preg_match('/^[0-9]+$/D', $googleCampaignId)) {
            throw new RuntimeException('Google campaign id must be numeric.');
        }

        $unsupportedTypes = $allowProximity ? "'LOCATION_GROUP'" : "'PROXIMITY', 'LOCATION_GROUP'";
        $unsupportedQuery = <<<GAQL
SELECT campaign_criterion.type
FROM campaign_criterion
WHERE campaign.id = {$googleCampaignId}
  AND campaign_criterion.type IN ({$unsupportedTypes})
  AND campaign_criterion.status != 'REMOVED'
GAQL;

        foreach ($this->search($connection, $unsupportedQuery, fresh: $fresh) as $chunk) {
            if (($chunk['results'] ?? []) !== []) {
                throw new RuntimeException('This Google campaign uses proximity or location-group targeting, which cannot be imported safely yet.');
            }
        }

        $query = <<<GAQL
SELECT
  campaign_criterion.resource_name,
  campaign_criterion.location.geo_target_constant,
  campaign_criterion.negative,
  campaign_criterion.status
FROM campaign_criterion
WHERE campaign.id = {$googleCampaignId}
  AND campaign_criterion.type = 'LOCATION'
  AND campaign_criterion.status != 'REMOVED'
GAQL;

        $criteria = collect($this->search($connection, $query, fresh: $fresh))
            ->flatMap(fn (mixed $chunk): array => is_array($chunk) ? ($chunk['results'] ?? []) : [])
            ->values();
        $resources = $criteria
            ->map(fn (array $row): string => (string) (data_get($row, 'campaignCriterion.location.geoTargetConstant')
                ?? data_get($row, 'campaign_criterion.location.geo_target_constant') ?? ''))
            ->unique()
            ->values()
            ->all();

        $metadata = $this->geoTargetMetadata($connection, $resources);

        return $criteria
            ->map(function (array $row) use ($includeStatus, $metadata): array {
                $criterion = (string) (data_get($row, 'campaignCriterion.resourceName')
                    ?? data_get($row, 'campaign_criterion.resource_name') ?? '');
                $geoTarget = (string) (data_get($row, 'campaignCriterion.location.geoTargetConstant')
                    ?? data_get($row, 'campaign_criterion.location.geo_target_constant') ?? '');

                if ($criterion === '' || ! isset($metadata[$geoTarget])) {
                    throw new RuntimeException('Google returned a location criterion without a usable identifier; import was cancelled.');
                }

                $location = $metadata[$geoTarget];

                $criterionData = [
                    'criterion' => $criterion,
                    'geo_target' => $geoTarget,
                    'country_code' => strtoupper((string) (data_get($location, 'geoTargetConstant.countryCode')
                        ?? data_get($location, 'geo_target_constant.country_code') ?? '')),
                    'target_type' => (string) (data_get($location, 'geoTargetConstant.targetType')
                        ?? data_get($location, 'geo_target_constant.target_type') ?? ''),
                    'name' => (string) (data_get($location, 'geoTargetConstant.canonicalName')
                        ?? data_get($location, 'geo_target_constant.canonical_name') ?? ''),
                    'negative' => (bool) (data_get($row, 'campaignCriterion.negative')
                        ?? data_get($row, 'campaign_criterion.negative') ?? false),
                ];

                if ($includeStatus) {
                    $criterionData['status'] = (string) (data_get($row, 'campaignCriterion.status')
                        ?? data_get($row, 'campaign_criterion.status') ?? '');
                }

                return $criterionData;
            })
            ->values()
            ->all();
    }

    /** @param list<string> $resources
     * @return array<string, array<string, mixed>>
     */
    private function geoTargetMetadata(GoogleAdsConnection $connection, array $resources): array
    {
        foreach ($resources as $resource) {
            if (! preg_match('/^geoTargetConstants\/[0-9]+$/D', $resource)) {
                throw new RuntimeException('Google returned a location criterion without a usable identifier; import was cancelled.');
            }
        }

        $metadata = [];

        foreach (array_chunk($resources, 100) as $batch) {
            $quoted = implode(', ', array_map(static fn (string $resource): string => "'{$resource}'", $batch));
            $lookup = "SELECT geo_target_constant.resource_name, geo_target_constant.country_code, geo_target_constant.target_type, geo_target_constant.canonical_name FROM geo_target_constant WHERE geo_target_constant.resource_name IN ({$quoted})";

            foreach ($this->search($connection, $lookup) as $chunk) {
                foreach ((array) ($chunk['results'] ?? []) as $row) {
                    $resource = (string) (data_get($row, 'geoTargetConstant.resourceName')
                        ?? data_get($row, 'geo_target_constant.resource_name') ?? '');

                    if (in_array($resource, $batch, true)) {
                        $metadata[$resource] = $row;
                    }
                }
            }
        }

        return $metadata;
    }

    /** @return list<array{latitude: float, longitude: float, radius: float, radius_unit: string, negative: bool, status: string}> */
    public function readCampaignProximityCriteria(GoogleAdsConnection $connection, string $googleCampaignId, bool $fresh = false): array
    {
        if (! preg_match('/^[0-9]+$/D', $googleCampaignId)) {
            throw new RuntimeException('Google campaign id must be numeric.');
        }

        $query = <<<GAQL
SELECT
  campaign_criterion.proximity.geo_point.latitude_in_micro_degrees,
  campaign_criterion.proximity.geo_point.longitude_in_micro_degrees,
  campaign_criterion.proximity.radius,
  campaign_criterion.proximity.radius_units,
  campaign_criterion.negative,
  campaign_criterion.status
FROM campaign_criterion
WHERE campaign.id = {$googleCampaignId}
  AND campaign_criterion.type = 'PROXIMITY'
  AND campaign_criterion.status != 'REMOVED'
GAQL;

        return collect($this->search($connection, $query, fresh: $fresh))
            ->flatMap(fn (mixed $chunk): array => is_array($chunk) ? ($chunk['results'] ?? []) : [])
            ->map(function (array $row): array {
                $proximity = data_get($row, 'campaignCriterion.proximity')
                    ?? data_get($row, 'campaign_criterion.proximity');
                $latitude = data_get($proximity, 'geoPoint.latitudeInMicroDegrees')
                    ?? data_get($proximity, 'geo_point.latitude_in_micro_degrees');
                $longitude = data_get($proximity, 'geoPoint.longitudeInMicroDegrees')
                    ?? data_get($proximity, 'geo_point.longitude_in_micro_degrees');
                $radius = data_get($proximity, 'radius');
                $unit = data_get($proximity, 'radiusUnits') ?? data_get($proximity, 'radius_units');

                if (! is_numeric($latitude) || ! is_numeric($longitude) || ! is_numeric($radius)
                    || ! in_array($unit, ['KILOMETERS', 'MILES'], true)) {
                    throw new RuntimeException('Google returned an incomplete proximity criterion. Review it before editing locations.');
                }

                return [
                    'latitude' => ((float) $latitude) / 1_000_000,
                    'longitude' => ((float) $longitude) / 1_000_000,
                    'radius' => (float) $radius,
                    'radius_unit' => $unit === 'MILES' ? 'mi' : 'km',
                    'negative' => (bool) (data_get($row, 'campaignCriterion.negative')
                        ?? data_get($row, 'campaign_criterion.negative') ?? false),
                    'status' => (string) (data_get($row, 'campaignCriterion.status')
                        ?? data_get($row, 'campaign_criterion.status') ?? ''),
                ];
            })->values()->all();
    }

    /**
     * Replace only the changed location criteria in one atomic Google mutate.
     * The caller must compare a fresh provider readback with the reviewed plan.
     *
     * @param  list<array{criterion: string, geo_target: string, negative: bool, status: string, target_type: string}>  $before
     * @param  list<string>  $afterIds
     */
    public function replaceCampaignLocationCriteria(GoogleAdsConnection $connection, string $googleCampaignId, array $before, array $afterIds): void
    {
        if (! preg_match('/^[0-9]+$/D', $googleCampaignId) || $afterIds === []
            || count($afterIds) !== count(array_unique($afterIds))) {
            throw new RuntimeException('Choose a valid Google campaign and a nonempty, unique location selection.');
        }

        $customerId = $this->customerId($connection);
        $campaignResource = 'customers/'.$customerId.'/campaigns/'.$googleCampaignId;
        $criterionPrefix = 'customers/'.$customerId.'/campaignCriteria/'.$googleCampaignId.'~';
        $existingByTarget = [];

        foreach ($before as $criterion) {
            $target = $criterion['geo_target'] ?? '';
            $resource = $criterion['criterion'] ?? '';

            if (! preg_match('/^geoTargetConstants\/[0-9]+$/D', $target)
                || ! str_starts_with($resource, $criterionPrefix)
                || ! preg_match('/^[0-9]+$/D', substr($resource, strlen($criterionPrefix)))
                || ($criterion['negative'] ?? true)
                || ($criterion['status'] ?? null) !== 'ENABLED'
                || ! in_array($criterion['target_type'] ?? null, ['Country', 'City', 'State', 'Province', 'Region', 'Territory'], true)
                || isset($existingByTarget[$target])) {
                throw new RuntimeException('Google returned an unsupported or mismatched location criterion. Review it before editing.');
            }

            $existingByTarget[$target] = $resource;
        }

        foreach ($afterIds as $id) {
            if (! preg_match('/^geoTargetConstants\/[0-9]+$/D', $id)) {
                throw new RuntimeException('A proposed Google location ID is invalid.');
            }
        }

        $operations = [];

        foreach (array_diff($afterIds, array_keys($existingByTarget)) as $id) {
            $operations[] = ['create' => [
                'campaign' => $campaignResource,
                'location' => ['geoTargetConstant' => $id],
            ]];
        }

        foreach (array_diff(array_keys($existingByTarget), $afterIds) as $id) {
            $operations[] = ['remove' => $existingByTarget[$id]];
        }

        if ($operations === []) {
            throw new RuntimeException('Google location targeting already matches the proposed selection.');
        }

        $this->mutateMany($connection, 'campaignCriteria', $operations, ['partialFailure' => false]);
    }

    /**
     * Resolve a targetable country by ISO code, never by an ambiguous name.
     *
     * @return array{id: string, name: string}|null
     */
    public function countryGeoTarget(GoogleAdsConnection $connection, string $countryCode, ?string $customerId = null): ?array
    {
        if (! preg_match('/^[A-Z]{2}$/D', $countryCode)) {
            throw new \InvalidArgumentException('Country code must contain two uppercase letters.');
        }

        $query = "SELECT geo_target_constant.resource_name, geo_target_constant.name, geo_target_constant.country_code, geo_target_constant.target_type, geo_target_constant.status FROM geo_target_constant WHERE geo_target_constant.country_code = '{$countryCode}' AND geo_target_constant.target_type = 'Country' AND geo_target_constant.status = 'ENABLED'";

        $matches = [];

        foreach ($this->search($connection, $query, $customerId) as $chunk) {
            foreach ((array) ($chunk['results'] ?? []) as $row) {
                $target = $row['geoTargetConstant'] ?? [];
                if (($target['countryCode'] ?? null) === $countryCode
                    && ($target['targetType'] ?? null) === 'Country'
                    && ($target['status'] ?? null) === 'ENABLED'
                    && filled($target['resourceName'] ?? null)) {
                    $matches[(string) $target['resourceName']] = [
                        'id' => (string) $target['resourceName'],
                        'name' => (string) ($target['name'] ?? ''),
                    ];
                }
            }
        }

        return count($matches) === 1 ? array_values($matches)[0] : null;
    }

    /**
     * Search targetable cities, first-level regions, or US DMA markets without
     * guessing from a name. Canonical names distinguish same-named places.
     *
     * @return list<array{id: string, name: string, label: string, country_code: string, kind: string, provider_type: string, parent_id: string|null}>
     */
    public function geoTargetCandidates(GoogleAdsConnection $connection, string $kind, string $countryCode, string $term, ?string $customerId = null): array
    {
        $types = match ($kind) {
            'city' => ['City'],
            'region' => ['State', 'Province', 'Region', 'Territory'],
            'dma' => ['DMA Region'],
            'postal' => ['Postal Code'],
            default => throw new \InvalidArgumentException('Search cities, regions, postal codes, or US DMA markets only.'),
        };

        if ($kind === 'dma' && $countryCode !== 'US') {
            throw new \InvalidArgumentException('DMA discovery is available for US markets only.');
        }

        if (! preg_match('/^[A-Z]{2}$/D', $countryCode)
            || ! preg_match('/^[\pL\pN .,-]{2,80}$/uD', trim($term))) {
            throw new \InvalidArgumentException('Provide a country code and a place or market name of 2 to 80 characters.');
        }

        $term = trim($term);
        $parts = array_map('trim', explode(',', $term, 2));

        if (count($parts) === 2 && (mb_strlen($parts[0]) < 2 || mb_strlen($parts[1]) < 2)) {
            throw new \InvalidArgumentException('Include a place name and a state or province after the comma.');
        }

        $name = $parts[0];
        $parentFilter = isset($parts[1]) ? " AND geo_target_constant.canonical_name LIKE '%{$parts[1]}%'" : '';
        $quotedTypes = implode(', ', array_map(fn (string $type): string => "'{$type}'", $types));
        $query = "SELECT geo_target_constant.resource_name, geo_target_constant.name, geo_target_constant.canonical_name, geo_target_constant.country_code, geo_target_constant.target_type, geo_target_constant.status, geo_target_constant.parent_geo_target FROM geo_target_constant WHERE geo_target_constant.country_code = '{$countryCode}' AND geo_target_constant.target_type IN ({$quotedTypes}) AND geo_target_constant.status = 'ENABLED' AND geo_target_constant.name LIKE '%{$name}%'{$parentFilter} ORDER BY geo_target_constant.canonical_name LIMIT 25";
        $candidates = [];

        foreach ($this->search($connection, $query, $customerId) as $chunk) {
            foreach ((array) ($chunk['results'] ?? []) as $row) {
                $target = $row['geoTargetConstant'] ?? [];

                if (($target['countryCode'] ?? null) !== $countryCode
                    || ($target['status'] ?? null) !== 'ENABLED'
                    || ! in_array($target['targetType'] ?? null, $types, true)
                    || ($kind === 'dma' && blank($target['parentGeoTarget'] ?? null))
                    || blank($target['resourceName'] ?? null)
                    || blank($target['name'] ?? null)
                    || blank($target['canonicalName'] ?? null)) {
                    continue;
                }

                $candidates[] = [
                    'id' => (string) $target['resourceName'],
                    'name' => (string) ($target['name'] ?? ''),
                    'label' => (string) ($target['canonicalName'] ?? $target['name'] ?? ''),
                    'country_code' => $countryCode,
                    'kind' => $kind,
                    'provider_type' => (string) $target['targetType'],
                    'parent_id' => $target['parentGeoTarget'] ?? null,
                ];
            }
        }

        return array_slice($candidates, 0, 25);
    }

    /**
     * Read a country's targetable places for a catalog import without a name filter.
     *
     * @return list<array{platform: string, external_id: string, kind: string, name: string, label: string, country_code: string, parent_external_id: string|null}>
     */
    public function geoTargetCatalog(GoogleAdsConnection $connection, string $kind, string $countryCode, string $customerId): array
    {
        $types = match ($kind) {
            'city' => ['City'],
            'region' => ['State', 'Province', 'Region', 'Territory'],
            'dma' => ['DMA Region'],
            default => throw new \InvalidArgumentException('Import cities, regions, or DMA markets only.'),
        };

        if (! preg_match('/^[A-Z]{2}$/D', $countryCode) || ($kind === 'dma' && $countryCode !== 'US')) {
            throw new \InvalidArgumentException('Provide a valid country for this location type.');
        }

        $quotedTypes = implode(', ', array_map(fn (string $type): string => "'{$type}'", $types));
        $query = "SELECT geo_target_constant.resource_name, geo_target_constant.name, geo_target_constant.canonical_name, geo_target_constant.country_code, geo_target_constant.target_type, geo_target_constant.status, geo_target_constant.parent_geo_target FROM geo_target_constant WHERE geo_target_constant.country_code = '{$countryCode}' AND geo_target_constant.target_type IN ({$quotedTypes}) AND geo_target_constant.status = 'ENABLED' ORDER BY geo_target_constant.canonical_name";
        $candidates = [];

        foreach ($this->search($connection, $query, $customerId) as $chunk) {
            foreach ((array) ($chunk['results'] ?? []) as $row) {
                $target = $row['geoTargetConstant'] ?? [];

                if (($target['countryCode'] ?? null) !== $countryCode
                    || ($target['status'] ?? null) !== 'ENABLED'
                    || ! in_array($target['targetType'] ?? null, $types, true)
                    || ($kind === 'dma' && blank($target['parentGeoTarget'] ?? null))
                    || blank($target['resourceName'] ?? null)
                    || blank($target['name'] ?? null)
                    || blank($target['canonicalName'] ?? null)) {
                    continue;
                }

                $candidates[] = [
                    'platform' => 'google',
                    'external_id' => (string) $target['resourceName'],
                    'kind' => $kind,
                    'name' => (string) $target['name'],
                    'label' => (string) $target['canonicalName'],
                    'country_code' => $countryCode,
                    'parent_external_id' => $target['parentGeoTarget'] ?? null,
                ];
            }
        }

        return $candidates;
    }

    private function search(GoogleAdsConnection $connection, string $query, ?string $customerId = null, bool $fresh = false): array
    {
        $customerId = $customerId !== null
            ? str_replace('-', '', $customerId)
            : $this->customerId($connection);
        $token = $this->accessToken($connection);
        $headers = [
            'developer-token' => GoogleAdsConnection::developerToken(),
            'Content-Type' => 'application/json',
        ];
        $loginCustomerId = $connection->manager_customer_id ?: config('services.google_ads.login_customer_id');
        if (filled($loginCustomerId)) {
            $headers['login-customer-id'] = str_replace('-', '', $loginCustomerId);
        }

        return $this->audited(
            'POST',
            'customers/'.$customerId.'/googleAds:searchStream',
            $customerId,
            ['query' => $query],
            mutating: false,
            fresh: $fresh,
            // $connection is captured because the URL needs its API version.
            //
            // It was left out, so every call through here died on "Undefined
            // variable $connection" before the request was made. It survived
            // review and merged because nothing called search() until the
            // location catalog import arrived with it: the method was dead code
            // from the commit that introduced the bug until the commit that
            // needed it, and a fatal in code nobody runs looks exactly like code
            // that works. The sibling call at line 93 captures it correctly.
            call: function () use ($connection, $token, $headers, $customerId, $query): array {
                $response = Http::withToken($token)
                    ->withHeaders($headers)
                    ->connectTimeout(5)
                    ->timeout(20)
                    ->post('https://googleads.googleapis.com/'.$this->apiVersion($connection).'/customers/'.$customerId.'/googleAds:searchStream', ['query' => $query]);

                return $this->handleMutationResponse($response);
            },
        );
    }

    public function updateCampaign(GoogleAdsConnection $connection, GoogleAdsCampaign $campaign, array $data): void
    {
        $customerId = $this->customerId($connection);
        $this->mutate($connection, 'campaigns', [
            'update' => [
                'resourceName' => 'customers/'.$customerId.'/campaigns/'.$campaign->google_campaign_id,
                'name' => $data['name'],
                'status' => $this->status($data['status']),
            ],
            'updateMask' => 'name,status',
        ]);

        if ($campaign->google_campaign_budget_id && array_key_exists('daily_budget', $data) && $data['daily_budget'] !== null) {
            $this->mutate($connection, 'campaignBudgets', [
                'update' => [
                    'resourceName' => 'customers/'.$customerId.'/campaignBudgets/'.$campaign->google_campaign_budget_id,
                    'amountMicros' => (string) round(((float) $data['daily_budget']) * 1000000),
                ],
                'updateMask' => 'amountMicros',
            ]);
        }
    }

    private function mutate(GoogleAdsConnection $connection, string $resource, array $operation): array
    {
        $customerId = $this->customerId($connection);
        $token = $this->accessToken($connection);
        $headers = [
            'developer-token' => GoogleAdsConnection::developerToken(),
            'Content-Type' => 'application/json',
        ];
        $loginCustomerId = $connection->manager_customer_id ?: config('services.google_ads.login_customer_id');
        if (filled($loginCustomerId)) {
            $headers['login-customer-id'] = str_replace('-', '', $loginCustomerId);
        }

        return $this->audited(
            'POST',
            'customers/'.$customerId.'/'.$resource.':mutate',
            $customerId,
            ['operations' => [$operation]],
            mutating: true,
            call: fn (): array => $this->handleMutationResponse(
                Http::withToken($token)
                    ->withHeaders($headers)
                    ->connectTimeout(5)
                    ->timeout(20)
                    ->post('https://googleads.googleapis.com/'.config('services.google_ads.api_version', 'v25').'/customers/'.$customerId.'/'.$resource.':mutate', [
                        'operations' => [$operation],
                    ]),
            ),
        );
    }

    /**
     * Native campaign criteria, including IDs for atomic, field-scoped replacement.
     *
     * @return list<array<string, mixed>>
     */
    public function readManagerCriteria(GoogleAdsConnection $connection, string $campaignId): array
    {
        if (! preg_match('/^[0-9]+$/D', $campaignId)) {
            throw new RuntimeException('Google campaign id must be numeric.');
        }

        $query = 'SELECT campaign_criterion.resource_name, campaign_criterion.type, campaign_criterion.status, campaign_criterion.negative, campaign_criterion.bid_modifier, '
            .'campaign_criterion.location.geo_target_constant, campaign_criterion.language.language_constant, campaign_criterion.device.type, '
            .'campaign_criterion.ad_schedule.day_of_week, campaign_criterion.ad_schedule.start_hour, campaign_criterion.ad_schedule.start_minute, '
            .'campaign_criterion.ad_schedule.end_hour, campaign_criterion.ad_schedule.end_minute '
            ."FROM campaign_criterion WHERE campaign.id = {$campaignId} AND campaign_criterion.status != 'REMOVED' "
            ."AND campaign_criterion.type IN ('LOCATION', 'LANGUAGE', 'DEVICE', 'AD_SCHEDULE')";
        $criteria = [];
        $prefix = 'customers/'.$this->customerId($connection).'/campaignCriteria/'.$campaignId.'~';
        foreach ($this->search($connection, $query, fresh: true) as $chunk) {
            foreach ($chunk['results'] ?? [] as $row) {
                $criterion = $row['campaignCriterion'] ?? [];
                if (! str_starts_with($criterion['resourceName'] ?? '', $prefix)
                    || ! ctype_digit(substr($criterion['resourceName'], strlen($prefix)))) {
                    throw new RuntimeException('Google returned a criterion outside this campaign.');
                }
                $path = match ($criterion['type'] ?? null) {
                    'LOCATION' => 'location.geoTargetConstant',
                    'LANGUAGE' => 'language.languageConstant',
                    'DEVICE' => 'device.type',
                    'AD_SCHEDULE' => 'adSchedule.dayOfWeek',
                    default => null,
                };
                if ($path === null || ! is_string(data_get($criterion, $path))
                    || data_get($criterion, $path) === ''
                    || ! in_array($criterion['status'] ?? null, ['ENABLED', 'PAUSED'], true)) {
                    throw new RuntimeException('Google returned an incomplete targeting criterion. The saved targeting was not replaced.');
                }
                $criteria[] = $criterion;
            }
        }

        usort($criteria, fn (array $a, array $b): int => strcmp($a['resourceName'], $b['resourceName']));

        return $criteria;
    }

    /** @return array<string, list<array<string, mixed>>> */
    public function readManagerAudiences(GoogleAdsConnection $connection, string $campaignId): array
    {
        if (! preg_match('/^[0-9]+$/D', $campaignId)) {
            throw new RuntimeException('Google campaign id must be numeric.');
        }

        $query = 'SELECT ad_group_criterion.resource_name, ad_group_criterion.ad_group, ad_group_criterion.type, ad_group_criterion.status, ad_group_criterion.negative, '
            .'ad_group_criterion.age_range.type, ad_group_criterion.gender.type, ad_group_criterion.user_list.user_list, '
            .'ad_group_criterion.user_interest.user_interest_category, ad_group_criterion.custom_audience.custom_audience, ad_group_criterion.combined_audience.combined_audience '
            ."FROM ad_group_criterion WHERE campaign.id = {$campaignId} AND ad_group_criterion.status != 'REMOVED' "
            ."AND ad_group_criterion.type IN ('AGE_RANGE','GENDER','USER_LIST','USER_INTEREST','CUSTOM_AUDIENCE','COMBINED_AUDIENCE')";
        $groups = [];
        $customer = $this->customerId($connection);
        foreach ($this->search($connection, $query, fresh: true) as $chunk) {
            foreach ($chunk['results'] ?? [] as $row) {
                $criterion = $row['adGroupCriterion'] ?? [];
                if (! preg_match('/^customers\/'.$customer.'\/adGroups\/([0-9]+)$/D', $criterion['adGroup'] ?? '', $match)
                    || ! preg_match('/^customers\/'.$customer.'\/adGroupCriteria\/'.$match[1].'~[0-9]+$/D', $criterion['resourceName'] ?? '')) {
                    throw new RuntimeException('Google returned an audience criterion outside the requested account or ad group.');
                }
                $path = match ($criterion['type'] ?? null) {
                    'AGE_RANGE' => 'ageRange.type',
                    'GENDER' => 'gender.type',
                    'USER_LIST' => 'userList.userList',
                    'USER_INTEREST' => 'userInterest.userInterestCategory',
                    'CUSTOM_AUDIENCE' => 'customAudience.customAudience',
                    'COMBINED_AUDIENCE' => 'combinedAudience.combinedAudience',
                    default => null,
                };
                if ($path === null || ! is_string(data_get($criterion, $path))
                    || data_get($criterion, $path) === ''
                    || ! in_array($criterion['status'] ?? null, ['ENABLED', 'PAUSED'], true)) {
                    throw new RuntimeException('Google returned an incomplete audience criterion. The saved audiences were not replaced.');
                }
                $groups[$match[1]][] = $criterion;
            }
        }
        foreach ($groups as &$criteria) {
            usort($criteria, fn (array $a, array $b): int => strcmp($a['resourceName'], $b['resourceName']));
        }
        unset($criteria);

        return $groups;
    }

    /**
     * Replaces the managed audience families only, leaving keywords, bids
     * and the ad group's targeting-vs-observation mode untouched.
     *
     * @param  list<array<string, mixed>>  $before
     * @param  list<array<string, mixed>>  $after
     */
    public function updateManagerAudiences(GoogleAdsConnection $connection, string $adGroupId, array $before, array $after): void
    {
        if (! ctype_digit($adGroupId)) {
            throw new RuntimeException('Google ad group id must be numeric.');
        }
        $customer = $this->customerId($connection);
        $known = [];
        foreach ($before as $criterion) {
            $resource = $criterion['resourceName'] ?? '';
            if (! preg_match('/^customers\/'.$customer.'\/adGroupCriteria\/'.$adGroupId.'~[0-9]+$/D', $resource)
                || ($criterion['status'] ?? null) !== 'ENABLED') {
                throw new RuntimeException('Google returned a foreign or paused audience criterion. Review it before editing.');
            }
            $content = array_diff_key($criterion, array_flip(['resourceName', 'adGroup', 'status']));
            $content['negative'] = (bool) ($content['negative'] ?? false);
            $known[json_encode(Canonical::sort($content))] = $resource;
        }
        $operations = [];
        $keep = [];
        foreach ($after as $criterion) {
            $criterion['negative'] = (bool) ($criterion['negative'] ?? false);
            $identity = json_encode(Canonical::sort($criterion));
            $keep[$identity] = true;
            if (! isset($known[$identity])) {
                $operations[] = ['create' => ['adGroup' => 'customers/'.$customer.'/adGroups/'.$adGroupId, ...array_diff_key($criterion, ['type' => true])]];
            }
        }
        foreach ($known as $identity => $resource) {
            if (! isset($keep[$identity])) {
                $operations[] = ['remove' => $resource];
            }
        }
        if ($operations !== []) {
            $this->mutateMany($connection, 'adGroupCriteria', $operations, ['partialFailure' => false]);
        }
    }

    /**
     * Only the requested criterion families change; unrelated audience and
     * geographic criteria are never removed. Google applies the batch atomically.
     *
     * @param  list<array<string, mixed>>  $before
     * @param  array<string, mixed>  $patch
     */
    public function updateManagerCriteria(GoogleAdsConnection $connection, string $campaignId, array $before, array $patch): void
    {
        if (! preg_match('/^[0-9]+$/D', $campaignId)) {
            throw new RuntimeException('Google campaign id must be numeric.');
        }

        $campaign = 'customers/'.$this->customerId($connection).'/campaigns/'.$campaignId;
        $prefix = 'customers/'.$this->customerId($connection).'/campaignCriteria/'.$campaignId.'~';
        $operations = [];
        foreach ($patch as $field => $values) {
            [$type, $key, $leaf, $negative] = match ($field) {
                'location_targets' => ['LOCATION', 'location', 'geoTargetConstant', false],
                'excluded_locations' => ['LOCATION', 'location', 'geoTargetConstant', true],
                'language_targets' => ['LANGUAGE', 'language', 'languageConstant', false],
                'delivery_schedule' => ['AD_SCHEDULE', 'adSchedule', null, false],
                'device_exclusions' => ['DEVICE', 'device', 'type', false],
                default => throw new RuntimeException('Unsupported Google targeting field.'),
            };
            $existing = array_filter($before, fn (array $row): bool => ($row['type'] ?? null) === $type && (bool) ($row['negative'] ?? false) === $negative);
            $byValue = [];
            foreach ($existing as $row) {
                $resource = $row['resourceName'] ?? '';
                if (! str_starts_with($resource, $prefix) || ! ctype_digit(substr($resource, strlen($prefix)))
                    || ($row['status'] ?? null) !== 'ENABLED' || ! is_array($row[$key] ?? null)) {
                    throw new RuntimeException('Google returned an unsupported or mismatched targeting criterion. Nothing was changed.');
                }
                $value = $leaf === null ? $row[$key] : ($row[$key][$leaf] ?? null);
                $byValue[json_encode(Canonical::sort([$value]))] = $row;
            }

            if ($field === 'device_exclusions') {
                foreach ($values as $device) {
                    if (! isset($byValue[json_encode([$device])])) {
                        throw new RuntimeException('Google did not report this device criterion. Its exclusion cannot safely be changed.');
                    }
                }
                foreach ($existing as $row) {
                    $excluded = (float) ($row['bidModifier'] ?? 1) === 0.0;
                    $exclude = in_array($row['device']['type'], $values, true);
                    if ($exclude !== $excluded) {
                        $operations[] = ['update' => ['resourceName' => $row['resourceName'], 'bidModifier' => $exclude ? 0 : 1], 'updateMask' => 'bid_modifier'];
                    }
                }

                continue;
            }

            $wanted = [];
            foreach ($values as $value) {
                $identity = json_encode(Canonical::sort([$value]));
                $wanted[$identity] = true;
                if (! isset($byValue[$identity])) {
                    $operations[] = ['create' => [
                        'campaign' => $campaign,
                        'negative' => $negative,
                        $key => $leaf === null ? $value : [$leaf => $value],
                    ]];
                }
            }
            foreach ($byValue as $identity => $row) {
                if (! isset($wanted[$identity])) {
                    $operations[] = ['remove' => $row['resourceName']];
                }
            }
        }

        if ($operations !== []) {
            $this->mutateMany($connection, 'campaignCriteria', $operations, ['partialFailure' => false]);
        }
    }

    private function mutateMany(GoogleAdsConnection $connection, string $resource, array $operations, array $options = []): array
    {
        $operationKey = $resource === 'googleAds' ? 'mutateOperations' : 'operations';
        $customerId = $this->customerId($connection);
        $token = $this->accessToken($connection);
        $headers = [
            'developer-token' => GoogleAdsConnection::developerToken(),
            'Content-Type' => 'application/json',
        ];
        $loginCustomerId = $connection->manager_customer_id ?: config('services.google_ads.login_customer_id');
        if (filled($loginCustomerId)) {
            $headers['login-customer-id'] = str_replace('-', '', $loginCustomerId);
        }

        return $this->audited(
            'POST',
            'customers/'.$customerId.'/'.$resource.':mutate',
            $customerId,
            [$operationKey => $operations, ...$options],
            mutating: true,
            call: fn (): array => $this->handleMutationResponse(
                Http::withToken($token)
                    ->withHeaders($headers)
                    ->connectTimeout(5)
                    ->timeout(20)
                    ->post('https://googleads.googleapis.com/'.config('services.google_ads.api_version', 'v25').'/customers/'.$customerId.'/'.$resource.':mutate', [
                        $operationKey => $operations,
                        ...$options,
                    ]),
            ),
        );
    }

    /**
     * A failed mutate, reported as Google reported it.
     *
     * Google answers with a generic top-level message - almost always "Request
     * contains an invalid argument." - and puts what is actually wrong in
     * `error.details[].errors[]`: a per-error `message` saying it in words, an
     * `errorCode` naming it, and a `location.fieldPathElements` saying which field
     * it is about. This kept the generic line and the enum, and threw the
     * sentences away, so a publish failed with "Request contains an invalid
     * argument. (DUPLICATE_CAMPAIGN_NAME)" when Google had said "The campaign name
     * is a duplicate" and named the field.
     *
     * The buyer reads this. It is the difference between a name they can change
     * and an error they can only forward to somebody.
     *
     * Kept on one line, because ChatController::readableFailure() takes the first
     * line of an exception message and a multi-line one would lose the rest.
     */
    private function handleMutationResponse($response): array
    {
        if (! $response->failed()) {
            return $response->json();
        }

        $payload = $response->json();
        if (is_array($payload) && array_is_list($payload)) {
            $payload = $payload[0] ?? [];
        }
        $errors = collect(data_get($payload, 'error.details', []))
            ->flatMap(fn (array $detail): array => $detail['errors'] ?? []);

        $codes = $errors
            ->pluck('errorCode')
            ->flatten()
            ->filter()
            ->unique()
            ->values();

        // The published-for-production case keeps its own explanation, because
        // Google's own wording for it says nothing a reader can act on.
        if ($codes->contains('CLOUD_PROJECT_NOT_APPROVED_FOR_PRODUCTION')) {
            throw new RuntimeException(
                'This Google Cloud project is not approved for production Google Ads accounts. '
                .'Use a Google Ads test account or request production access for the developer '
                .'token and OAuth project.'
            );
        }

        $reasons = $errors
            ->map(function (array $error): ?string {
                $said = trim((string) ($error['message'] ?? ''));

                if ($said === '') {
                    return null;
                }

                // Flattened, because ChatController::readableFailure() takes the
                // first line of an exception message and Google's own text is
                // sometimes several.
                $said = trim((string) preg_replace('/\s+/', ' ', $said));

                $field = collect(data_get($error, 'location.fieldPathElements', []))
                    ->pluck('fieldName')
                    ->filter()
                    ->implode('.');

                return $field === '' ? $said : rtrim($said, '.').' ['.$field.']';
            })
            ->filter()
            ->unique()
            ->values();

        $message = $reasons->isNotEmpty()
            ? 'Google refused it: '.$reasons->implode('; ')
            : (string) data_get($payload, 'error.message', 'Google Ads API request failed.');

        if ($codes->isNotEmpty()) {
            $message .= ' ('.$codes->implode(', ').')';
        }

        throw new RuntimeException($message);
    }

    private function accessToken(GoogleAdsConnection $connection): string
    {
        $config = $this->adsConfig($connection);
        $refreshToken = filled($connection->refresh_token)
            ? $connection->refresh_token
            : (string) ($config['refresh_token'] ?? '');

        if (blank($refreshToken)) {
            throw new RuntimeException('Google OAuth token refresh failed. Reconnect the Google Ads account.');
        }

        // One exchange per token lifetime, not one per API call.
        //
        // This ran on every request and the result was thrown away: measured at
        // five exchanges for four Ads API calls, because it sits outside
        // audited() so CallLogger's read memoisation cannot help it, and the
        // structure reads pass fresh: true which disables memoisation anyway.
        // That doubled the latency of every Google operation, spent Google's
        // token-endpoint quota, and appeared in no audit row.
        //
        // Keyed by a hash of the credentials, so rotating the refresh token or
        // the client id stops the old token being served. The token itself is
        // what is cached and it is already a bearer secret; the key is hashed
        // so the refresh token is not one.
        $cacheKey = 'google-ads-access-token:'.hash(
            'sha256',
            GoogleAdsConnection::oauthClientId().'|'.$refreshToken,
        );

        if (is_string($cached = Cache::get($cacheKey)) && $cached !== '') {
            return $cached;
        }

        $response = Http::asForm()->connectTimeout(5)->timeout(10)->post('https://oauth2.googleapis.com/token', [
            'client_id' => GoogleAdsConnection::oauthClientId(),
            'client_secret' => GoogleAdsConnection::oauthClientSecret(),
            'refresh_token' => $refreshToken,
            'grant_type' => 'refresh_token',
        ]);

        if ($response->failed() || ! is_string($response->json('access_token'))) {
            throw new RuntimeException('Google OAuth token refresh failed. Reconnect the Google Ads account.');
        }

        $token = (string) $response->json('access_token');

        // A minute short of what Google says, so a token cached at the start of
        // a long turn cannot expire part way through it. Failures are never
        // cached: only a token that was actually issued is kept.
        $lifetime = max(60, (int) ($response->json('expires_in') ?? 3600) - 60);

        Cache::put($cacheKey, $token, $lifetime);

        return $token;
    }

    /**
     * @return array<string, mixed>
     */
    private function adsConfig(GoogleAdsConnection $connection): array
    {
        return config('services.google_ads', []);
    }

    private function developerToken(GoogleAdsConnection $connection): string
    {
        return (string) ($this->adsConfig($connection)['developer_token'] ?? '');
    }

    private function apiVersion(GoogleAdsConnection $connection): string
    {
        return (string) ($this->adsConfig($connection)['api_version'] ?? 'v25');
    }

    private function loginCustomerId(GoogleAdsConnection $connection): ?string
    {
        if (filled($connection->manager_customer_id)) {
            return str_replace('-', '', (string) $connection->manager_customer_id);
        }

        $fromConfig = $this->adsConfig($connection)['login_customer_id'] ?? null;

        return filled($fromConfig) ? str_replace('-', '', (string) $fromConfig) : null;
    }

    /**
     * @return array<string, string>
     */
    private function requestHeaders(GoogleAdsConnection $connection): array
    {
        $headers = [
            'developer-token' => $this->developerToken($connection),
            'Content-Type' => 'application/json',
        ];
        $loginCustomerId = $this->loginCustomerId($connection);

        if ($loginCustomerId !== null) {
            $headers['login-customer-id'] = $loginCustomerId;
        }

        return $headers;
    }

    private function customerId(GoogleAdsConnection $connection): string
    {
        if (blank($connection->customer_id) || blank($connection->refresh_token)) {
            throw new RuntimeException('Connect Google Ads and select a customer account first.');
        }

        return str_replace('-', '', $connection->customer_id);
    }

    private function firstResourceName(array $response, string $resultKey): ?string
    {
        $mutateResponses = data_get($response, 'mutateOperationResponses', []);
        if (is_array($mutateResponses) && $mutateResponses !== []) {
            $resourceName = data_get($mutateResponses[0], $resultKey.'.resourceName');
            if (is_string($resourceName) && $resourceName !== '') {
                return $resourceName;
            }
        }

        $results = data_get($response, 'results', []);
        if (is_array($results) && $results !== []) {
            $resourceName = data_get($results[0], 'resourceName');
            if (is_string($resourceName) && $resourceName !== '') {
                return $resourceName;
            }
        }

        return null;
    }

    private function resourceId(?string $resourceName): string
    {
        if (! is_string($resourceName) || ! preg_match('/(?:\/|~)(\d+)$/', $resourceName, $matches)) {
            throw new RuntimeException('Google Ads returned an incomplete campaign response.');
        }

        return $matches[1];
    }

    private function status(string $status): string
    {
        return $status === 'enabled' ? 'ENABLED' : 'PAUSED';
    }
}
