<?php

namespace App\Campaigns;

use App\Agent\Workspace;
use App\Campaigns\Platforms\Platforms;
use App\Models\ArtifactFieldSource;
use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
use App\Services\LinkedIn\LinkedIn;
use App\Services\LinkedIn\LinkedInUrn;
use App\Services\Meta\Meta;
use App\Services\Platforms\Support\Guardrails;
use App\Support\Actor;
use App\Support\CurrencyMinorUnits;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use RuntimeException;

/**
 * Adopt a campaign that already exists on the platform.
 *
 * Everything the product could touch until now, it had built itself. Most of
 * what a media buyer actually works on was made elsewhere, and was untouchable:
 * no local row, no ids, and above all no baseline to diff against.
 *
 * The baseline is the point. published_state is what the platform is believed
 * to hold, and every later edit is a comparison against it. Adopting without
 * one would make the first edit look like a change to every field at once.
 *
 * Values are read over Graph, never the MCP. The MCP renders them for people,
 * "$25.00 USD" rather than 2500, so a value read there cannot be compared with
 * a new one or written back.
 */
class CampaignImporter
{
    public function __construct(
        private readonly Meta $meta,
        private readonly GoogleAdsService $google,
        private readonly PendingChanges $pending,
        private readonly Workspace $workspace,
        private readonly Guardrails $guardrails,
        private readonly Actor $actor,
        private readonly ?LinkedIn $linkedin = null,
    ) {}

    public function adoptLinkedIn(string $campaignId, string $accountId, Model $owner): Campaign
    {
        $campaignId = LinkedInUrn::numericId($campaignId) ?? throw new RuntimeException('Choose a numeric LinkedIn campaign ID or URN.');
        $accountId = LinkedInUrn::numericId($accountId) ?? throw new RuntimeException('Choose a numeric LinkedIn account ID or URN.');
        $this->guardrails->assertAccountAllowed($accountId, 'linkedin');
        $existing = Campaign::query()->where('platform', 'linkedin')->where('ad_account_id', $accountId)
            ->whereIn('external_campaign_id', [$campaignId, LinkedInUrn::campaign($campaignId)])->first();
        if ($existing !== null && (string) $existing->user_id !== (string) $owner->getKey()) {
            throw new RuntimeException('This LinkedIn campaign is already managed by another user.');
        }
        $profile = ($this->linkedin ?? app(LinkedIn::class))->on($existing?->id, $this->actor->describe('campaign import'))->campaign($accountId, $campaignId);
        if (LinkedInUrn::numericId((string) ($profile['id'] ?? '')) !== $campaignId) {
            throw new RuntimeException('LinkedIn returned a different campaign than requested.');
        }
        $profileFields = $this->linkedInProfileFields($profile);
        if ($existing !== null) {
            $baseline = (array) $existing->published_state;
            $current = $this->pending->snapshot($existing);
            if ($baseline === []) {
                $baseline = $current;
            }
            $updates = ['meta' => [...(array) $existing->meta, 'linkedin_import' => $profile], 'last_synced_at' => now()];
            foreach ($profileFields as $field => $value) {
                if (($current[$field] ?? null) === ($baseline[$field] ?? null)) {
                    $updates[$field] = $value;
                }
                if (array_key_exists($field, $baseline)) {
                    $baseline[$field] = match (true) {
                        $value instanceof \DateTimeInterface => $value->format('Y-m-d H:i:s'),
                        in_array($field, ['budget', 'bid_amount'], true) && is_numeric($value) => number_format((float) $value, 2, '.', ''),
                        is_numeric($value) => (string) $value,
                        default => $value,
                    };
                }
            }
            if (array_key_exists('campaignGroup', $profile)) {
                $updates['external_ids'] = [...(array) $existing->external_ids,
                    'campaign_group_id' => LinkedInUrn::numericId((string) $profile['campaignGroup'])];
            }
            $existing->update([...$updates, 'published_state' => $baseline]);

            return $existing->fresh();
        }
        $campaign = Campaign::create([
            'user_id' => $owner->getKey(), 'platform' => 'linkedin', 'status' => 'published',
            'name' => 'Imported LinkedIn campaign', 'ad_account_id' => $accountId,
            'external_campaign_id' => $campaignId, 'budget_level' => 'campaign',
            'bid_strategy' => 'AUTOMATED_BID', ...$profileFields,
            'external_ids' => ['campaign_id' => $campaignId, 'campaign_group_id' => LinkedInUrn::numericId((string) ($profile['campaignGroup'] ?? ''))],
            'meta' => ['linkedin_import' => $profile], 'last_synced_at' => now(),
        ]);
        $campaign->forceFill(['published_state' => $this->pending->snapshot($campaign)])->save();
        $this->recordWhereItCameFrom($campaign);

        return $campaign->fresh();
    }

    /** @return array<string, mixed> */
    private function linkedInProfileFields(array $profile): array
    {
        $fields = [];
        if (isset($profile['name'])) {
            $fields['name'] = preg_replace('/^ARB-/', '', (string) $profile['name']);
        }
        if (isset($profile['objectiveType'])) {
            // LinkedIn's enum is singular and the internal names are plural, so
            // every singular form has to be named here. JOB_APPLICANT and
            // WEBSITE_CONVERSION were missing, and an imported campaign on
            // either kept LinkedIn's spelling, which is not one of
            // LinkedInRules::objectives() - so the publish gate called the
            // adopted campaign's own objective unsupported.
            $fields['objective'] = match ($profile['objectiveType']) {
                'WEBSITE_VISIT' => 'WEBSITE_VISITS',
                'VIDEO_VIEW' => 'VIDEO_VIEWS',
                'JOB_APPLICANT', 'JOB_APPLICANTS' => 'JOB_APPLY',
                'WEBSITE_CONVERSION' => 'WEBSITE_CONVERSIONS',
                default => $profile['objectiveType'],
            };
        }
        $budget = $profile['dailyBudget'] ?? $profile['totalBudget'] ?? null;
        if (is_array($budget)) {
            if (array_key_exists('amount', $budget)) {
                $fields['budget'] = $budget['amount'];
            }
            if (array_key_exists('currencyCode', $budget)) {
                $fields['currency'] = $budget['currencyCode'];
            }
            $fields['budget_mode'] = isset($profile['dailyBudget']) ? 'daily' : 'lifetime';
        }
        if (isset($profile['optimizationTargetType']) || array_key_exists('unitCost', $profile)) {
            $optimization = (string) ($profile['optimizationTargetType'] ?? '');
            $fields['bid_strategy'] = match (true) {
                str_starts_with($optimization, 'TARGET_') => 'TARGET_COST',
                str_starts_with($optimization, 'MAX_') => 'AUTOMATED_BID',
                (float) ($profile['unitCost']['amount'] ?? 0) > 0 => 'MAXIMUM_BID',
                default => 'AUTOMATED_BID',
            };
            $fields['bid_amount'] = $profile['unitCost']['amount'] ?? null;
        }
        if (array_key_exists('associatedEntity', $profile)) {
            $fields['page_id'] = LinkedInUrn::numericId((string) $profile['associatedEntity']);
        }
        if (is_array($profile['runSchedule'] ?? null)) {
            if (isset($profile['runSchedule']['start'])) {
                $fields['starts_at'] = Carbon::createFromTimestampMs($profile['runSchedule']['start']);
            }
            $fields['ends_at'] = isset($profile['runSchedule']['end'])
                ? Carbon::createFromTimestampMs($profile['runSchedule']['end']) : null;
        }

        return $fields;
    }

    /**
     * Adopt a Google campaign from an allowed customer account.
     *
     * The account used to be the configured one, always, because that was the
     * only one anybody could publish to. Once the allow list opened and the
     * flow began asking which of the manager's children to buy on, a campaign
     * id from any of the other accounts simply could not be opened: the read
     * went to the configured customer and Google said the campaign did not
     * exist, which is true of that account and useless to the buyer.
     *
     * A campaign is addressed by id alone, and an id does not say which account
     * holds it. Searching every permitted account would mean one read per
     * account - 76 on this manager - to answer a question the buyer can answer
     * in one click, so where there is a choice to make this asks rather than
     * sweeping. Where there is only one permitted account there is nothing to
     * ask and it is used, which is the behaviour this has always had.
     */
    public function adoptGoogle(string $campaignId, Model $owner, string $accountId = ''): Campaign
    {
        if (! preg_match('/^[0-9]+$/D', $campaignId)) {
            throw new RuntimeException('Google campaign id must be numeric.');
        }

        $connection = GoogleAdsConnection::shared()
            ?? throw new RuntimeException(GoogleAdsConnection::missingReason());

        $named = preg_replace('/\D/', '', $accountId) ?: '';
        $accountId = $named !== '' ? $named : str_replace('-', '', (string) $connection->customer_id);

        $this->guardrails->assertAccountAllowed($accountId, 'google');
        $connection = $connection->onCustomer($accountId);

        $existing = Campaign::query()
            ->where('platform', 'google')
            ->where('ad_account_id', $accountId)
            ->where('external_campaign_id', $campaignId)
            ->first();

        if ($existing !== null) {
            if ((string) $existing->user_id !== (string) $owner->getKey()) {
                throw new RuntimeException('This Google campaign is already managed by another user.');
            }

            return $existing;
        }

        try {
            $profile = $this->google->readCampaignProfile($connection, $campaignId);
        } catch (RuntimeException $e) {
            // Not in the account we looked in. Where that was a guess - the
            // configured account, because the caller named none - and other
            // accounts are permitted, the campaign may well be in one of them
            // and the buyer is the cheapest way to find out. One read per
            // permitted account would be 76 on this manager to answer a
            // question worth one click.
            if ($named === '' && app(Platforms::class)->for('google')->accountChoiceExists()) {
                throw new RuntimeException(sprintf(
                    'Campaign %s is not in Google Ads account %s, and more than one account is '
                    .'permitted. A campaign id does not say which account holds it: call '
                    .'list_ad_accounts to put them on screen, then open the campaign again with the '
                    .'account it belongs to.',
                    $campaignId,
                    $accountId,
                ), 0, $e);
            }

            throw $e;
        }
        if ($profile['id'] !== $campaignId) {
            throw new RuntimeException('Google returned a different campaign than the one requested.');
        }

        $criteria = $this->google->readCampaignLocationCriteria($connection, $campaignId, allowProximity: true);
        $proximities = $this->google->readCampaignProximityCriteria($connection, $campaignId);

        if (collect($proximities)->contains(fn (array $proximity): bool => $proximity['negative']
            || $proximity['status'] !== 'ENABLED')) {
            throw new RuntimeException('Google returned unsupported or paused proximity targeting. Import was cancelled.');
        }
        $countries = collect($criteria)
            ->filter(fn (array $criterion): bool => ! $criterion['negative'] && strtolower($criterion['target_type']) === 'country')
            ->pluck('country_code')
            ->filter(fn (string $code): bool => (bool) preg_match('/^[A-Z]{2}$/D', $code))
            ->unique()
            ->values()
            ->all();
        $channel = strtoupper($profile['advertising_channel_type']);
        $campaignType = match ($channel) {
            'SEARCH' => 'search',
            'DISPLAY' => 'display',
            'PERFORMANCE_MAX' => 'performance_max',
            default => null,
        };
        $searchCriteria = $campaignType === 'search'
            ? $this->google->readCampaignSearchCriteria($connection, $campaignId)
            : [];

        $campaign = Campaign::query()->create([
            'user_id' => $owner->getKey(),
            'name' => $profile['name'] ?: 'Imported Google campaign',
            'platform' => 'google',
            'campaign_type' => $campaignType,
            'status' => 'published',
            'ad_account_id' => $accountId,
            'budget' => $profile['daily_budget'],
            'budget_level' => 'campaign',
            'budget_mode' => 'daily',
            'starts_at' => $profile['start_date'] ?: null,
            'locations' => $criteria === [] && $proximities === [] ? null : [
                'countries' => $countries,
                'google_location_criteria' => $criteria,
                ...($proximities === [] ? [] : ['google_proximity_criteria' => $proximities]),
            ],
            'external_campaign_id' => $campaignId,
            'external_ids' => [
                'campaign_id' => $campaignId,
                ...preg_match('/^customers\/[0-9]+\/campaignBudgets\/([0-9]+)$/D', $profile['budget_resource'] ?? '', $budgetMatch)
                    ? ['budget_id' => $budgetMatch[1]]
                    : [],
                'budget_reference_count' => $profile['budget_reference_count'],
                ...($campaignType === 'search' ? ['google_ad_group_criteria' => $searchCriteria] : []),
            ],
            'last_synced_at' => now(),
        ]);

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

        return $campaign->fresh();
    }

    /**
     * Bring a platform campaign under management.
     *
     * Idempotent by external id: adopting the same campaign twice returns the
     * row already held rather than making a second one that would then fight
     * with the first over the same objects.
     *
     * Idempotent for the owner, that is. The lookup is by external id alone, so
     * anybody who could name a campaign id got back the row somebody else owns -
     * and with it that campaign's objective, budget, targeting and ad copy, all
     * of which the chat then reads out. Two accounts on the same ad account is
     * the ordinary case here, which is what makes the id guessable: it is in the
     * Ads Manager URL of every campaign a colleague can see. adoptGoogle() twenty
     * lines up has always refused this.
     */
    public function adopt(string $campaignId, Model $owner): Campaign
    {
        if ($existing = Campaign::where('platform', 'meta')->where('external_campaign_id', $campaignId)->first()) {
            if ((string) $existing->user_id !== (string) $owner->getKey()) {
                throw new RuntimeException('This Meta campaign is already managed by another user.');
            }

            return $existing;
        }

        // The account first, and only the account.
        //
        // A campaign is addressed by its own id, so the allow list cannot be
        // consulted before the first request: accountIn() finds an account only
        // when the endpoint starts with one. This used to read the whole campaign
        // and check afterwards, which refused the adoption but had already
        // pulled budget, objective, bidding, schedule and special ad categories
        // off an account we are not permitted to touch - into the response, into
        // the call log, and into our database as a logged request body.
        //
        // One field cannot be avoided: something has to tell us whose campaign
        // this is. Everything past that field now waits for permission.
        $accountId = $this->normalizedAccountId($this->meta->campaignAccountId($campaignId));

        if (blank($accountId)) {
            throw new RuntimeException("Meta returned no campaign for {$campaignId}.");
        }

        $this->guardrails->assertAccountAllowed($accountId, 'meta');

        // Scoped to the account from here on, so every later call is one the
        // guardrail can vet before it is made rather than after.
        $remote = $this->meta->campaign($campaignId, $accountId);

        if (! isset($remote['id'])) {
            throw new RuntimeException("Meta returned no campaign for {$campaignId}.");
        }

        $adSets = $this->meta->adSets($campaignId, $accountId);

        // Budget, bidding, schedule and targeting live on the ad set, not the
        // campaign. Multiple ad sets are common; the first is adopted and the
        // rest are recorded so nothing silently disappears.
        $adSet = $adSets[0] ?? [];

        // The account's currency, read once, because every money field below is
        // in its minor units and the yen has none. Without it a JPY campaign
        // imported as a hundred times its real budget, and was then republished
        // at that figure. Stored on the campaign too: nothing else sets it on
        // this path, so a later edit would have guessed again.
        $currency = $this->accountCurrency($accountId);
        $budget = $this->budget($remote, $adSet, $currency);

        $campaign = new Campaign([
            'user_id' => $owner->getKey(),
            'name' => $remote['name'] ?? 'Imported campaign',
            'platform' => 'meta',
            'status' => 'published',
            // The account that was checked, not the one the second read
            // reported: writing a different id than the guardrail approved
            // would put the campaign under an account nothing ever vetted.
            'ad_account_id' => $accountId,
            // Only when the account actually told us. The column is not
            // nullable, so writing null here fails the insert outright, and a
            // guessed currency is worse than the column's own default.
            ...filled($currency) ? ['currency' => $currency] : [],
            'objective' => $remote['objective'] ?? null,
            'special_ad_categories' => $this->declaredCategories($remote),
            'optimization_goal' => $adSet['optimization_goal'] ?? null,
            'pixel_id' => $adSet['promoted_object']['pixel_id'] ?? null,
            'budget' => $budget['amount'],
            'budget_level' => $budget['level'],
            'budget_mode' => $budget['mode'],
            'bid_strategy' => $remote['bid_strategy'] ?? $adSet['bid_strategy'] ?? null,
            'bid_amount' => $this->money($adSet['bid_amount'] ?? null, $currency),
            'starts_at' => $this->time($adSet['start_time'] ?? null),
            // A campaign-level lifetime budget puts the end on the campaign as
            // stop_time, and the ad set may carry none.
            'ends_at' => $this->time($adSet['end_time'] ?? $remote['stop_time'] ?? null),
            'locations' => $this->locations($adSet),
            'placements' => $this->placements($adSet),
            'external_campaign_id' => $campaignId,
            'external_ids' => [
                ...$this->ids($campaignId, $adSets),
                'meta_custom_audience_criteria' => $this->metaCustomAudienceCriteria($adSets),
            ],
            'last_synced_at' => now(),
        ]);

        $campaign->save();

        $this->adoptAdSets($campaign, $adSets, $currency);

        // The baseline, written from what was just read, so the campaign starts
        // with nothing pending rather than appearing to have changed entirely.
        $campaign->forceFill(['published_state' => $this->pending->snapshot($campaign)])->save();

        $this->recordWhereItCameFrom($campaign);

        return $campaign->fresh();
    }

    /**
     * Every ad set the campaign actually has, as rows.
     *
     * The first one's settings came in through the campaign's own attributes,
     * which is where they belong, so this only has to give it its platform id
     * and its real name. The rest used to be listed in
     * external_ids['other_adset_ids'] and nothing else: "recorded, not
     * managed", so an edit reached the first ad set and silently ignored the
     * others, and a buyer had no way to see they existed. They are rows with
     * their own targeting, schedule and money now.
     *
     * @param  list<array<string,mixed>>  $adSets
     */
    private function adoptAdSets(Campaign $campaign, array $adSets, ?string $currency): void
    {
        if (($first = $campaign->primaryAdSet) !== null) {
            $first->update(array_filter([
                'name' => $adSets[0]['name'] ?? null,
                'external_adset_id' => $adSets[0]['id'] ?? null,
            ], fn (mixed $value): bool => filled($value)) + ['status' => 'published']);
        }

        foreach (array_slice($adSets, 1) as $index => $adSet) {
            // Its own amount, read off the ad set alone. budget() prefers the
            // campaign's, which is right for deciding where a campaign holds
            // its money and wrong here: every ad set under an Advantage
            // campaign budget would come back holding the campaign's total.
            $budget = $this->budget([], $adSet, $currency);

            $campaign->adSets()->create([
                'position' => $index + 2,
                'name' => $adSet['name'] ?? $campaign->name.' - ad set '.($index + 2),
                'locations' => $this->locations($adSet),
                'placements' => $this->placements($adSet),
                'optimization_goal' => $adSet['optimization_goal'] ?? null,
                'conversion_event' => $adSet['promoted_object']['custom_event_type'] ?? null,
                'budget' => $budget['amount'],
                'budget_mode' => $budget['amount'] === null ? null : $budget['mode'],
                'bid_strategy' => $adSet['bid_strategy'] ?? null,
                'bid_amount' => $this->money($adSet['bid_amount'] ?? null, $currency),
                'starts_at' => $this->time($adSet['start_time'] ?? null),
                'ends_at' => $this->time($adSet['end_time'] ?? null),
                'external_adset_id' => $adSet['id'] ?? null,
                'status' => 'published',
            ]);
        }
    }

    /**
     * Where this campaign's budget actually is, and what kind it is.
     *
     * The campaign is looked at first: if it holds a budget then it is using
     * Advantage campaign budget, and the ad set has none. Reading the ad set
     * first would report a campaign-budget campaign as having no budget, and
     * any later edit would then be pushed at the wrong object.
     *
     * @param  array<string,mixed>  $remote
     * @param  array<string,mixed>  $adSet
     * @return array{amount: float|null, level: string, mode: string}
     */
    private function budget(array $remote, array $adSet, ?string $currency = null): array
    {
        foreach ([['campaign', $remote], ['adset', $adSet]] as [$level, $object]) {
            foreach (['daily' => 'daily_budget', 'lifetime' => 'lifetime_budget'] as $mode => $field) {
                if ($amount = $this->money($object[$field] ?? null, $currency)) {
                    return ['amount' => $amount, 'level' => $level, 'mode' => $mode];
                }
            }
        }

        return ['amount' => null, 'level' => 'adset', 'mode' => 'daily'];
    }

    /**
     * Say that these values came from the platform, because they did.
     *
     * Nothing was recorded at all, so every row of an adopted campaign showed
     * the grey dot the panel uses for "not set" while displaying a real value
     * read from Meta. The dots exist to separate what a person chose from what
     * was guessed, and an adopted campaign is the case where neither applies:
     * the platform is the source, and there is a colour for exactly that.
     */
    private function recordWhereItCameFrom(Campaign $campaign): void
    {
        $fields = [
            'name', 'objective', 'optimization_goal', 'special_ad_categories',
            'ad_account_id', 'pixel_id', 'budget', 'budget_level', 'budget_mode',
            'bid_strategy', 'bid_amount', 'starts_at', 'ends_at', 'locations', 'placements',
        ];

        foreach ($fields as $field) {
            // Only what Meta actually returned. A field it had nothing for is
            // still unanswered, and saying otherwise would hide a real gap.
            if (blank($campaign->getAttribute($field))) {
                continue;
            }

            $this->workspace->recordSource($campaign, $field, ArtifactFieldSource::PLATFORM_RETURNED);
        }
    }

    /**
     * The special ad category declaration, as it stands on the platform.
     *
     * Adopted rather than asked for again. Whoever built the campaign already
     * made this declaration to Meta, and it is a statement about the
     * advertising, not a preference: asking a second time invites a different
     * answer from the one Meta is holding.
     *
     * Meta writes "no category" as an empty list, and null here means nobody
     * has ever been asked, so the two cannot share a representation. An empty
     * list from Meta becomes our own NONE, which is an answer. The field
     * missing from the response is the only genuine unknown, and leaves the
     * flow asking, which is the safe direction.
     *
     * @param  array<string,mixed>  $remote
     * @return list<string>|null
     */
    private function declaredCategories(array $remote): ?array
    {
        if (! array_key_exists('special_ad_categories', $remote)) {
            return null;
        }

        $declared = array_values(array_filter((array) $remote['special_ad_categories']));

        return $declared === [] ? ['NONE'] : $declared;
    }

    /**
     * Money as Meta states it.
     *
     * Budgets and bids come back as minor units in a string, "2500" for $25.
     * Read as a number it becomes a budget a hundred times too large, which is
     * the kind of mistake that only shows up on the invoice.
     */
    /**
     * The account's own currency, which decides what a minor unit is.
     *
     * A read failure is not fatal here: the rest of the import is still worth
     * having, and a null currency falls through to the two-decimal default,
     * which is what this code assumed unconditionally before.
     */
    private function accountCurrency(?string $adAccountId): ?string
    {
        if (blank($adAccountId)) {
            return null;
        }

        try {
            return $this->meta->adAccount($adAccountId)['currency'] ?? null;
        } catch (\Throwable) {
            return null;
        }
    }

    private function money(int|string|null $minorUnits, ?string $currency = null): ?float
    {
        return $minorUnits === null || $minorUnits === ''
            ? null
            : CurrencyMinorUnits::toMajor($minorUnits, $currency);
    }

    private function time(?string $value): ?string
    {
        return $value ? Carbon::parse($value)->toDateTimeString() : null;
    }

    /** @return array<string,mixed>|null */
    private function locations(array $adSet): ?array
    {
        $geo = $adSet['targeting']['geo_locations'] ?? null;
        $countries = $geo['countries'] ?? null;

        if (! is_array($geo)) {
            return null;
        }

        $locations = $countries ? ['countries' => array_values($countries)] : [];

        if (array_diff(array_keys($geo), ['countries']) !== []) {
            $locations['meta_geo_locations'] = $geo;
        }

        return $locations ?: null;
    }

    /**
     * Retain each imported ad set's audience choices at its original scope.
     * These provider rows are a read-only baseline, not editable draft choices.
     *
     * @param  list<array<string, mixed>>  $adSets
     * @return list<array<string, mixed>>
     */
    private function metaCustomAudienceCriteria(array $adSets): array
    {
        $criteria = [];

        foreach ($adSets as $adSet) {
            $targeting = (array) ($adSet['targeting'] ?? []);
            $included = $targeting['custom_audiences'] ?? [];
            $excluded = $targeting['excluded_custom_audiences'] ?? [];

            if (! is_array($included) || ! is_array($excluded)) {
                throw new RuntimeException('Meta returned incomplete custom-audience targeting; import was cancelled.');
            }

            if ($included === [] && $excluded === []) {
                continue;
            }

            if (blank($adSet['id'] ?? null)) {
                throw new RuntimeException('Meta returned an audience without its ad-set ID; import was cancelled.');
            }

            foreach ([...$included, ...$excluded] as $audience) {
                if (! is_array($audience) || ! preg_match('/^[0-9]+$/D', (string) ($audience['id'] ?? ''))) {
                    throw new RuntimeException('Meta returned an audience without a usable ID; import was cancelled.');
                }
            }

            $criteria[] = [
                'adset_id' => (string) $adSet['id'],
                'custom_audiences' => array_values($included),
                'excluded_custom_audiences' => array_values($excluded),
            ];
        }

        return $criteria;
    }

    /**
     * Placements as we hold them: the platforms, not every position.
     *
     * Meta returns publisher_platforms plus a list of positions per platform.
     * Only the platforms are ours to edit, so only they are adopted, and the
     * positions are left alone on the platform rather than half represented.
     *
     * @return list<string>|null
     */
    private function placements(array $adSet): ?array
    {
        $platforms = $adSet['targeting']['publisher_platforms'] ?? null;

        return $platforms ? array_values($platforms) : null;
    }

    /** Meta reports account_id bare; everything here addresses it as act_<id>. */
    private function normalizedAccountId(?string $id): ?string
    {
        // A prefix strip. ltrim() with a character list would eat any leading
        // a, c, t or underscore, so an account id that happened to start with
        // one would come back mangled.
        return filled($id) ? 'act_'.preg_replace('/^act_/', '', $id) : null;
    }

    /**
     * @param  list<array<string,mixed>>  $adSets
     * @return array<string,mixed>
     */
    private function ids(string $campaignId, array $adSets): array
    {
        $ids = ['campaign_id' => $campaignId];

        if (isset($adSets[0]['id'])) {
            $ids['adset_id'] = $adSets[0]['id'];
        }

        // other_adset_ids used to be listed here, with a note that they were
        // recorded rather than managed. Every ad set is a row now, so the rows
        // are the record and a second copy of the ids would be one more thing
        // to keep in step.
        return $ids;
    }
}
