<?php

namespace App\Services\Meta;

use App\Services\Platforms\Support\CallContext;
use App\Services\Platforms\Support\CallLogger;
use App\Support\PublicHttp;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

/**
 * The Meta Graph API, called with the system user token.
 *
 * Used for everything the Ads MCP cannot do: reading accounts, pages and
 * pixels, uploading local files, and deleting. Also used for creation when the
 * MCP is switched off.
 */
class GraphApi
{
    public function __construct(
        private readonly string $token,
        private readonly string $version,
        private readonly CallLogger $log,
        private readonly string $fallbackToken = '',
    ) {}

    // ------------------------------------------------------------------ read

    /**
     * Every ad account the token can see, following the pages.
     *
     * One page of 50 was all this read, so a token that can see more than that
     * silently showed a truncated chooser - and once the allow list is served
     * from this call rather than from one lookup per account, a truncation here
     * turns into an extra call per account it missed. Paged the same way pages()
     * is, with the same style of cap.
     *
     * @return list<array<string, mixed>>
     */
    public function adAccounts(int $limit = 50): array
    {
        $accounts = [];
        $after = null;

        do {
            $response = $this->get('me/adaccounts', array_filter([
                'fields' => 'id,name,account_status,currency,timezone_name',
                'limit' => $limit,
                'after' => $after,
            ], fn (mixed $value): bool => $value !== null && $value !== ''));

            array_push($accounts, ...($response['data'] ?? []));
            $after = data_get($response, 'paging.cursors.after');
        } while (is_string($after) && $after !== '' && count($accounts) < 500);

        return $accounts;
    }

    /**
     * A current still of one creative.
     *
     * The address stored at sync time is signed and later answers "URL signature
     * expired". Asking Graph again returns one that still downloads. image_url
     * is the creative; thumbnail_url is the fallback when that field is empty.
     */
    public function creativeImageUrl(string $creativeId, ?string $adAccountId = null): ?string
    {
        $creativeId = trim($creativeId);
        $adAccountId = trim((string) $adAccountId);

        if ($this->token === '' || preg_match('/^[0-9]+$/', $creativeId) !== 1) {
            return null;
        }

        $body = $this->get($creativeId, [
            'fields' => 'image_url,thumbnail_url',
        ], $adAccountId !== '' ? $adAccountId : null);

        foreach (['image_url', 'thumbnail_url'] as $field) {
            $url = $body[$field] ?? null;

            if (is_string($url) && PublicHttp::isPublicUrl($url)) {
                return $url;
            }
        }

        return null;
    }

    /**
     * @throws MetaException when the account is unreachable
     */
    public function adAccount(string $adAccountId, bool $fresh = false): array
    {
        return $this->get($this->prefixed($adAccountId), [
            // user_tasks is what this token is allowed to do on this account:
            // DRAFT, ANALYZE, ADVERTISE, MANAGE. Reading it is how an account we
            // cannot create ads on gets refused when it is chosen, rather than
            // ten questions later when the first creative is uploaded.
            'fields' => 'id,name,account_status,disable_reason,currency,timezone_name,business,user_tasks',
        ], fresh: $fresh);
    }

    /**
     * Names Meta will accept as the verified advertiser on an ad set.
     *
     * The account defaults come first. A verified business on the account is
     * included too. An unverified business name is not offered: Meta rejects it
     * with the same error the missing field produces.
     *
     * @return list<string>
     */
    public function verifiedAdvertisers(string $adAccountId): array
    {
        $account = $this->get($this->prefixed($adAccountId), [
            'fields' => 'default_dsa_beneficiary,default_dsa_payor,business{id,name,verification_status}',
        ], fresh: true);

        $names = [];

        foreach (['default_dsa_beneficiary', 'default_dsa_payor'] as $field) {
            $name = trim((string) ($account[$field] ?? ''));

            if ($name !== '') {
                $names[$name] = $name;
            }
        }

        $business = is_array($account['business'] ?? null) ? $account['business'] : [];
        $businessName = trim((string) ($business['name'] ?? ''));
        $verified = in_array(strtolower((string) ($business['verification_status'] ?? '')), ['verified', 'approved'], true);

        if ($businessName !== '' && $verified) {
            $names[$businessName] = $businessName;
        }

        return array_values($names);
    }

    /**
     * Verified advertiser ids already saved on this account's ad sets.
     *
     * Meta does not list the ids behind the Ads Manager dropdown. An ad set
     * that was saved there carries them, and a later create has to send those
     * ids. The display name alone is refused with subcode 3858634.
     *
     * @return list<array{beneficiary_id: string, payer_id: string, beneficiary_name: string, payer_name: string, categories: list<string>}>
     */
    public function verifiedAdvertiserIdentities(string $adAccountId): array
    {
        $found = [];
        $names = [];
        $after = null;
        $seen = 0;

        do {
            $response = $this->get($this->prefixed($adAccountId).'/adsets', array_filter([
                'fields' => 'id,name,dsa_beneficiary,dsa_payor,regional_regulated_categories,regional_regulation_identities',
                'limit' => 50,
                'after' => $after,
            ], static fn (mixed $value): bool => $value !== null), fresh: true);

            foreach ((array) ($response['data'] ?? []) as $row) {
                $seen++;

                if (! is_array($row)) {
                    continue;
                }

                $identities = is_array($row['regional_regulation_identities'] ?? null)
                    ? $row['regional_regulation_identities']
                    : [];
                $beneficiary = trim((string) ($identities['universal_beneficiary'] ?? ''));
                $payer = trim((string) ($identities['universal_payer'] ?? ''));

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

                if ($payer === '') {
                    $payer = $beneficiary;
                }

                $key = $beneficiary.'|'.$payer;

                if (isset($found[$key])) {
                    continue;
                }

                $categories = [];

                foreach ((array) ($row['regional_regulated_categories'] ?? []) as $category) {
                    if (is_string($category) && $category !== '') {
                        $categories[] = $category;
                    }
                }

                $beneficiaryName = trim((string) ($row['dsa_beneficiary'] ?? ''));
                $payerName = trim((string) ($row['dsa_payor'] ?? ''));

                if ($beneficiaryName === '') {
                    $beneficiaryName = $this->identityName($beneficiary, $names);
                }

                if ($payerName === '' && $payer !== $beneficiary) {
                    $payerName = $this->identityName($payer, $names);
                }

                $found[$key] = [
                    'beneficiary_id' => $beneficiary,
                    'payer_id' => $payer,
                    'beneficiary_name' => $beneficiaryName,
                    'payer_name' => $payerName,
                    'categories' => array_values(array_unique($categories)),
                ];
            }

            $after = data_get($response, 'paging.cursors.after');
        } while (is_string($after) && $after !== '' && $seen < 200);

        return array_values($found);
    }

    /**
     * The display name of a verified-identity id.
     *
     * An ad set can carry the id with no dsa_beneficiary. The id alone is what
     * the choice button showed.
     *
     * @param  array<string, string>  $names
     */
    private function identityName(string $id, array &$names): string
    {
        if (array_key_exists($id, $names)) {
            return $names[$id];
        }

        try {
            $node = $this->get($id, ['fields' => 'name'], fresh: true);
            $names[$id] = trim((string) ($node['name'] ?? ''));
        } catch (MetaException) {
            $names[$id] = '';
        }

        return $names[$id];
    }

    /** @return list<array<string, mixed>> */
    public function customAudiences(string $adAccountId, bool $fresh = false): array
    {
        $audiences = [];
        $after = null;

        do {
            $response = $this->get($this->prefixed($adAccountId).'/customaudiences', array_filter([
                'fields' => 'id,name,account_id,subtype,pixel_id,operation_status,delivery_status,approximate_count_lower_bound,approximate_count_upper_bound',
                'limit' => 100,
                'after' => $after,
            ], static fn (mixed $value): bool => $value !== null), fresh: $fresh);

            array_push($audiences, ...(array) ($response['data'] ?? []));
            $after = data_get($response, 'paging.cursors.after');
        } while (is_string($after) && $after !== '' && count($audiences) < 500);

        return array_slice($audiences, 0, 500);
    }

    /**
     * Normalize whitespace and casing for both Meta's query and cache identity.
     *
     * @return list<array<string, mixed>>
     */
    public function targetingInterests(string $adAccountId, string $query): array
    {
        $query = trim($query);

        if (! preg_match('/^[\pL\pN ._\x27&()-]{2,80}$/uD', $query)) {
            throw new \InvalidArgumentException('Enter an audience idea between 2 and 80 characters.');
        }

        return $this->targetingSearch($adAccountId, $query, 'interests');
    }

    /**
     * Detailed targeting Meta will actually accept for this account.
     *
     * limit_type is one of the catalog's search types: interests, behaviors,
     * education, work, family, life events, or a device list. The path on each
     * row is where Meta files it today, which can differ from the menu branch
     * the buyer started in.
     *
     * @return list<array<string, mixed>>
     */
    public function targetingSearch(string $adAccountId, string $query, string $limitType): array
    {
        $query = trim($query);

        if (! preg_match('/^[\pL\pN ._\x27&()-]{2,80}$/uD', $query)
            || ! MetaTargetingCatalog::acceptsLimit($limitType)) {
            throw new \InvalidArgumentException('Search a supported Meta audience type with 2 to 80 characters.');
        }

        $query = mb_strtolower(preg_replace('/\s+/u', ' ', $query));

        return (array) ($this->get($this->prefixed($adAccountId).'/targetingsearch', [
            'q' => $query,
            'limit' => 25,
            'limit_type' => $limitType,
        ], $adAccountId)['data'] ?? []);
    }

    /**
     * The live browse tree for one targeting type.
     *
     * Categories stay in our menu. Subcategories and the options under them
     * come from this call, because a hardcoded name is not a Meta id.
     *
     * targetingbrowse accepts interests and behaviors. It rejects
     * limit_type=demographics, so that tree comes from the category search.
     *
     * @return list<array<string, mixed>>
     */
    public function targetingBrowse(string $adAccountId, string $limitType): array
    {
        if (! in_array($limitType, ['interests', 'behaviors', 'demographics'], true)) {
            throw new \InvalidArgumentException('Browse interests, behaviors, or demographics.');
        }

        if ($limitType === 'demographics') {
            return $this->targetingCategories($adAccountId, 'demographics');
        }

        $rows = [];
        $after = null;

        for ($page = 0; $page < 5; $page++) {
            $query = ['limit_type' => $limitType, 'limit' => 200];

            if (is_string($after) && $after !== '') {
                $query['after'] = $after;
            }

            $response = $this->get($this->prefixed($adAccountId).'/targetingbrowse', $query, $adAccountId);
            $batch = array_values(array_filter(
                (array) ($response['data'] ?? []),
                'is_array',
            ));
            $rows = [...$rows, ...$batch];
            $after = $response['paging']['cursors']['after'] ?? null;

            if (! is_string($after) || $after === '' || $batch === []) {
                break;
            }
        }

        return $rows;
    }

    /**
     * Every option in a targeting class, including demographics.
     *
     * Meta's browse endpoint has no demographics limit type. This search is
     * the call that returns that tree, with each row's own type and path.
     *
     * @return list<array<string, mixed>>
     */
    private function targetingCategories(string $adAccountId, string $class): array
    {
        $rows = [];
        $after = null;

        for ($page = 0; $page < 5; $page++) {
            $query = [
                'type' => 'adTargetingCategory',
                'class' => $class,
                'limit' => 500,
            ];

            if (is_string($after) && $after !== '') {
                $query['after'] = $after;
            }

            $response = $this->get('search', $query, $adAccountId);
            $batch = array_values(array_filter(
                (array) ($response['data'] ?? []),
                'is_array',
            ));
            $rows = [...$rows, ...$batch];
            $after = $response['paging']['cursors']['after'] ?? null;

            if (! is_string($after) || $after === '' || $batch === []) {
                break;
            }
        }

        return $rows;
    }

    /**
     * Related targeting Meta suggests from options the buyer already picked.
     *
     * @param  list<array{type: string, id: string}>  $targetingList
     * @return list<array<string, mixed>>
     */
    public function targetingSuggestions(string $adAccountId, array $targetingList): array
    {
        if ($targetingList === [] || count($targetingList) > 10) {
            throw new \InvalidArgumentException('Suggest from one to ten saved Meta targeting options.');
        }

        $encoded = json_encode($targetingList, JSON_THROW_ON_ERROR);

        return (array) ($this->get($this->prefixed($adAccountId).'/targetingsuggestions', [
            'targeting_list' => $encoded,
            'limit' => 15,
        ], $adAccountId)['data'] ?? []);
    }

    /**
     * Whether this targeting spec is large enough for Meta to deliver.
     *
     * @param  array<string, mixed>  $targetingSpec
     * @return array<string, mixed>
     */
    public function deliveryEstimate(string $adAccountId, string $optimizationGoal, array $targetingSpec): array
    {
        if ($optimizationGoal === '' || $targetingSpec === []) {
            throw new \InvalidArgumentException('A delivery estimate needs an optimization goal and a targeting spec.');
        }

        return $this->get($this->prefixed($adAccountId).'/delivery_estimate', [
            'optimization_goal' => $optimizationGoal,
            'targeting_spec' => json_encode($targetingSpec, JSON_THROW_ON_ERROR),
        ], $adAccountId);
    }

    /** @param list<string> $ids
     * @return list<array<string, mixed>>
     */
    public function validateTargetingInterests(string $adAccountId, array $ids): array
    {
        if ($ids === [] || count($ids) > 20
            || collect($ids)->contains(fn (string $id): bool => ! preg_match('/^[0-9]+$/D', $id))) {
            throw new \InvalidArgumentException('Choose up to 20 Meta interests from the current results.');
        }

        return $this->validateTargetingOptions($adAccountId, 'interests', $ids);
    }

    /**
     * @param  list<string>  $ids
     * @return list<array<string, mixed>>
     */
    public function validateTargetingOptions(string $adAccountId, string $type, array $ids): array
    {
        if ($ids === [] || count($ids) > MetaTargetingCatalog::MAX_PER_FIELD
            || ! MetaTargetingCatalog::acceptsLimit($type)
            || collect($ids)->contains(fn (string $id): bool => ! preg_match('/^[0-9]+$/D', $id))) {
            throw new \InvalidArgumentException('Choose up to '.MetaTargetingCatalog::MAX_PER_FIELD.' Meta targeting options from the current results.');
        }

        return (array) ($this->get($this->prefixed($adAccountId).'/targetingvalidation', [
            'targeting_list' => json_encode(array_map(
                static fn (string $id): array => ['type' => $type, 'id' => $id],
                $ids,
            ), JSON_THROW_ON_ERROR),
        ], $adAccountId)['data'] ?? []);
    }

    /** @return array<string, mixed> */
    public function createWebsiteAudience(
        string $adAccountId,
        string $name,
        string $pixelId,
        string $eventName,
        int $retentionDays,
    ): array {
        $name = trim($name);
        $eventName = trim($eventName);

        if (! preg_match('/^act_[0-9]+$/D', $adAccountId)
            || ! preg_match('/^[0-9]+$/D', $pixelId)
            || $name === '' || mb_strlen($name) > 255
            || $eventName === '' || mb_strlen($eventName) > 100
            || $retentionDays < 1 || $retentionDays > 180) {
            throw new \InvalidArgumentException('Provide a valid account, pixel, event, audience name, and retention window.');
        }

        $rule = [
            'inclusions' => [
                'operator' => 'or',
                'rules' => [[
                    'event_sources' => [['id' => $pixelId, 'type' => 'pixel']],
                    'retention_seconds' => $retentionDays * 86400,
                    'filter' => [
                        'operator' => 'and',
                        'filters' => [[
                            'field' => 'event',
                            'operator' => '=',
                            'value' => $eventName,
                        ]],
                    ],
                ]],
            ],
        ];

        return $this->post($this->prefixed($adAccountId).'/customaudiences', [
            'name' => $name,
            'description' => 'Website visitors who fired '.$eventName.' in the last '.$retentionDays.' days.',
            'rule' => json_encode($rule, JSON_THROW_ON_ERROR),
            'retention_days' => $retentionDays,
            'prefill' => true,
        ]);
    }

    /**
     * Languages Meta can target, as a name and the locale number an ad set stores.
     *
     * Used when a live ad set's language is being changed. Creation does not call this.
     *
     * @return list<array{locale: int, name: string}>
     */
    public function adLocales(string $query, ?string $adAccountId = null): array
    {
        $query = trim($query);

        if ($query === '' || mb_strlen($query) > 80) {
            throw new \InvalidArgumentException('Name a language to search for.');
        }

        $rows = (array) ($this->get('search', [
            'type' => 'adlocale',
            'q' => $query,
            'limit' => 25,
        ], $adAccountId)['data'] ?? []);

        $locales = [];

        foreach ($rows as $row) {
            if (! is_array($row) || ! is_numeric($row['key'] ?? null) || ! filled($row['name'] ?? null)) {
                continue;
            }

            $locales[] = ['locale' => (int) $row['key'], 'name' => (string) $row['name']];
        }

        return $locales;
    }

    /**
     * Interests Ads Manager shows for a typed search.
     *
     * @return list<array{id: string, name: string, audience_size: int}>
     */
    public function adInterests(string $adAccountId, string $query): array
    {
        return $this->adCatalogSearch($adAccountId, 'adinterest', $query);
    }

    /**
     * Job titles, filed under demographics as work_positions.
     *
     * @return list<array{id: string, name: string, audience_size: int}>
     */
    public function adWorkPositions(string $adAccountId, string $query): array
    {
        return $this->adCatalogSearch($adAccountId, 'adworkposition', $query);
    }

    /**
     * Interests related to names the buyer already has.
     *
     * @param  list<string>  $names
     * @return list<array{id: string, name: string, audience_size: int}>
     */
    public function adInterestSuggestions(string $adAccountId, array $names): array
    {
        $names = array_values(array_filter(array_map(
            static fn (string $name): string => trim($name),
            $names,
        ), static fn (string $name): bool => $name !== ''));

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

        $rows = (array) ($this->get('search', [
            'type' => 'adinterestsuggestion',
            'interest_list' => json_encode(array_slice($names, 0, 10), JSON_THROW_ON_ERROR),
            'limit' => 15,
        ], $adAccountId)['data'] ?? []);

        return $this->adCatalogRows($rows);
    }

    /**
     * @return list<array{id: string, name: string, audience_size: int}>
     */
    private function adCatalogSearch(string $adAccountId, string $type, string $query): array
    {
        $query = trim($query);

        if (! preg_match('/^[\pL\pN ._\x27&()-]{2,80}$/uD', $query)) {
            throw new \InvalidArgumentException('Search Meta targeting with 2 to 80 characters.');
        }

        $rows = (array) ($this->get('search', [
            'type' => $type,
            'q' => $query,
            'limit' => 25,
        ], $adAccountId)['data'] ?? []);

        return $this->adCatalogRows($rows);
    }

    /**
     * @param  list<mixed>  $rows
     * @return list<array{id: string, name: string, audience_size: int}>
     */
    private function adCatalogRows(array $rows): array
    {
        $items = [];

        foreach ($rows as $row) {
            if (! is_array($row)) {
                continue;
            }

            $id = trim((string) ($row['id'] ?? ''));
            $name = trim((string) ($row['name'] ?? ''));

            if ($id === '' || $name === '' || preg_match('/^[0-9]+$/D', $id) !== 1) {
                continue;
            }

            $lower = $row['audience_size_lower_bound'] ?? $row['audience_size'] ?? 0;
            $items[] = ['id' => $id, 'name' => $name, 'audience_size' => is_numeric($lower) ? (int) $lower : 0];
        }

        return $items;
    }

    /** @return list<array<string, mixed>> */
    public function countryCandidates(string $countryName, ?string $adAccountId = null): array
    {
        return (array) ($this->get('search', [
            'type' => 'adgeolocation',
            'location_types' => json_encode(['country']),
            'q' => $countryName,
        ], $adAccountId)['data'] ?? []);
    }

    /** @return list<array<string, mixed>> */
    public function locationCandidates(string $kind, string $countryCode, string $term, ?string $adAccountId = null, int $page = 1): array
    {
        if (! in_array($kind, ['city', 'region', 'dma', 'postal'], true)
            || ! preg_match('/^[A-Z]{2}$/D', $countryCode)
            || ! preg_match('/^[\pL\pN .\x27,&()-]{2,80}$/uD', trim($term))
            || $page < 1 || $page > 4) {
            throw new \InvalidArgumentException('Provide a country code and a place or market name of 2 to 80 characters.');
        }

        $after = null;

        for ($current = 1; $current <= $page; $current++) {
            $response = $this->get('search', array_filter([
                'type' => 'adgeolocation',
                'location_types' => json_encode([match ($kind) {
                    'dma' => 'geo_market', 'postal' => 'zip', default => $kind,
                }]),
                'country_code' => $countryCode,
                'q' => trim($term),
                'limit' => 25,
                'after' => $after,
            ], fn (mixed $value): bool => $value !== null), $adAccountId);

            if ($current === $page) {
                return (array) ($response['data'] ?? []);
            }

            $after = data_get($response, 'paging.cursors.after');

            if (! is_string($after) || $after === '') {
                return [];
            }
        }

        return [];
    }

    /**
     * Regions Meta will accept in one country.
     *
     * One search term does not list a country. These few broad terms, each
     * read at the high limit, together return every US state and Washington
     * D.C. The key on each row is Meta's.
     *
     * @return list<array<string, mixed>>
     */
    public function regionsInCountry(string $countryCode, ?string $adAccountId = null): array
    {
        if (! preg_match('/^[A-Z]{2}$/D', $countryCode)) {
            throw new \InvalidArgumentException('Provide a two-letter country code.');
        }

        $found = [];
        $failure = null;

        foreach (['al', 'st', 'or', 'en'] as $term) {
            try {
                $rows = (array) ($this->get('search', [
                    'type' => 'adgeolocation',
                    'location_types' => json_encode(['region']),
                    'country_code' => $countryCode,
                    'q' => $term,
                    'limit' => 100,
                ], $adAccountId)['data'] ?? []);
            } catch (MetaException $exception) {
                $failure = $exception;

                continue;
            }

            foreach ($rows as $row) {
                if (! is_array($row)) {
                    continue;
                }

                $key = trim((string) ($row['key'] ?? ''));

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

                $found[$key] = $row;
            }
        }

        if ($found === [] && $failure !== null) {
            throw $failure;
        }

        return array_values($found);
    }

    /** Validate one provider market key against the intended ad account without creating an ad. */
    public function marketAudienceEstimate(string $adAccountId, string $marketKey): int
    {
        if (! preg_match('/^COMSCORE_MARKET:[0-9]+$/D', $marketKey)) {
            throw new MetaException('Choose an exact Meta market key.');
        }

        $response = $this->get($this->prefixed($adAccountId).'/reachestimate', [
            'targeting_spec' => json_encode(['geo_locations' => ['geo_markets' => [['key' => $marketKey]]]], JSON_THROW_ON_ERROR),
        ], $adAccountId);
        $estimate = $response['data'] ?? null;

        if (! is_array($estimate) || ($estimate['estimate_ready'] ?? null) !== true
            || ! is_numeric($estimate['users_upper_bound'] ?? null)
            || (int) $estimate['users_upper_bound'] <= 0) {
            throw new MetaException('Meta did not confirm an audience for this market on the selected ad account.');
        }

        return (int) $estimate['users_upper_bound'];
    }

    /**
     * Every Page the token can publish from, following Meta's paging.
     *
     * This asked for 50 and stopped, so an account with more than fifty Pages
     * simply never saw the rest and the buyer was told their Page did not
     * exist. Meta returns a cursor rather than a total, so the only way to know
     * there are more is to follow it.
     *
     * Bounded at 500 because a chooser is not a directory, and an unbounded
     * loop against someone else's API is a way to hang a web request.
     *
     * @return list<array<string,mixed>>
     */
    public function pages(int $limit = 50, bool $fresh = false): array
    {
        $pages = [];
        $after = null;

        do {
            $response = $this->get('me/accounts', array_filter([
                'fields' => 'id,name,category',
                'limit' => $limit,
                'after' => $after,
            ], fn (mixed $value): bool => $value !== null && $value !== ''), fresh: $fresh);

            array_push($pages, ...($response['data'] ?? []));
            $after = data_get($response, 'paging.cursors.after');
        } while (is_string($after) && $after !== '' && count($pages) < 500);

        return $pages;
    }

    /**
     * Instagram accounts the ads could run as.
     *
     * Two sources, because they answer different questions. The one connected
     * to the Page is the account an Instagram placement will use by default,
     * and is what the buyer almost always means. The ad account's own list is
     * everything else it has permission to run as, which is how a brand with
     * several handles picks a different one.
     *
     * Both edges return an empty list rather than failing when there is no
     * Instagram presence at all, which is a real and ordinary case.
     *
     * @return list<array{id: string, username: string|null, source: string}>
     */
    public function instagramAccounts(string $adAccountId, ?string $pageId = null): array
    {
        $accounts = [];

        if ($pageId) {
            // Both Page fields, because Meta keeps two and they can disagree.
            //
            // connected_instagram_account is the older linkage;
            // instagram_business_account is the Business or Creator account
            // linked in Page settings, and is the one Meta's own ads
            // documentation points at. A Page can carry the second without the
            // first, and reading only one field reported no Instagram presence
            // for a Page that visibly has one.
            //
            // Asked for in the same request, so this costs a field rather than
            // a call, and the pair is deduplicated by id below.
            $connected = $this->get($pageId, [
                'fields' => 'connected_instagram_account{id,username},instagram_business_account{id,username}',
            ]);

            foreach (['connected_instagram_account', 'instagram_business_account'] as $field) {
                $id = data_get($connected, $field.'.id');

                if (! $id || isset($accounts[$id])) {
                    continue;
                }

                $accounts[$id] = [
                    'id' => (string) $id,
                    'username' => data_get($connected, $field.'.username'),
                    'source' => 'connected to the Page',
                ];
            }
        }

        foreach ($this->get($this->prefixed($adAccountId).'/instagram_accounts', [
            'fields' => 'id,username',
            'limit' => 50,
        ])['data'] ?? [] as $account) {
            $id = (string) ($account['id'] ?? '');

            if ($id === '' || isset($accounts[$id])) {
                continue;
            }

            $accounts[$id] = [
                'id' => $id,
                'username' => $account['username'] ?? null,
                'source' => 'on the ad account',
            ];
        }

        return array_values($accounts);
    }

    /**
     * Campaigns already on an account, whoever built them.
     *
     * Read over Graph rather than the MCP on purpose: the MCP returns values
     * shaped for people, "$25.00 USD" and "Cost per result goal", which cannot
     * be written back. Anything we intend to edit has to be read as the API
     * states it.
     *
     * @return list<array<string,mixed>>
     */
    public function campaigns(string $adAccountId, int $limit = 100): array
    {
        return $this->get($this->prefixed($adAccountId).'/campaigns', [
            'fields' => 'id,name,status,effective_status,objective,buying_type,created_time,updated_time',
            'limit' => $limit,
        ])['data'] ?? [];
    }

    /**
     * One campaign, as the API states it.
     *
     * The budget fields are here as well as on the ad set because a campaign
     * using Advantage campaign budget holds the money itself, and reading only
     * the ad set makes such a campaign look like it has no budget at all.
     */
    /** @param  bool  $fresh  bypass the in-request memo, for reading back a write made in the same request */
    public function campaign(string $campaignId, ?string $adAccountId = null, bool $fresh = false): array
    {
        return $this->get($campaignId, [
            'fields' => 'id,name,status,effective_status,objective,buying_type,account_id,'
                .'special_ad_categories,'
                .'daily_budget,lifetime_budget,bid_strategy,spend_cap,start_time,stop_time,created_time,updated_time',
        ], $adAccountId, $fresh);
    }

    /**
     * Active and paused campaigns, with the budget and bid strategy set on them.
     *
     * The ordinary campaign list leaves the money off, and it does not say it
     * is limited to campaigns that can still deliver. Archived and deleted
     * campaigns are excluded here. A paused campaign is included: pausing
     * stops delivery, it does not remove the budget or the spend.
     *
     * @return list<array<string, mixed>>
     */
    public function deliveryCampaigns(string $adAccountId, int $limit = 26): array
    {
        return $this->get($this->prefixed($adAccountId).'/campaigns', [
            'fields' => 'id,name,status,effective_status,daily_budget,lifetime_budget,bid_strategy',
            'filtering' => json_encode([[
                'field' => 'effective_status',
                'operator' => 'IN',
                'value' => ['ACTIVE', 'PAUSED'],
            ]], JSON_THROW_ON_ERROR),
            'limit' => $limit,
        ], $adAccountId, fresh: true)['data'] ?? [];
    }

    /**
     * Ad sets under one campaign, with budget, bid, and campaign-budget spend limits.
     *
     * status rather than effective_status: an ad set under a paused campaign
     * is CAMPAIGN_PAUSED and would otherwise disappear from a read of that
     * campaign. Archived and deleted ad sets stay out.
     *
     * @return list<array<string, mixed>>
     */
    public function deliveryAdSets(string $campaignId, ?string $adAccountId = null, int $limit = 50): array
    {
        return $this->get($campaignId.'/adsets', [
            'fields' => 'id,name,status,effective_status,daily_budget,lifetime_budget,bid_strategy,bid_amount,'
                .'bid_constraints,pacing_type,daily_min_spend_target,daily_spend_cap,lifetime_min_spend_target,lifetime_spend_cap,'
                .'start_time,end_time,adset_schedule,targeting,optimization_goal,promoted_object,'
                .'destination_type,billing_event,attribution_spec,is_dynamic_creative',
            'filtering' => json_encode([[
                'field' => 'status',
                'operator' => 'IN',
                'value' => ['ACTIVE', 'PAUSED'],
            ]], JSON_THROW_ON_ERROR),
            'limit' => $limit,
        ], $adAccountId, fresh: true)['data'] ?? [];
    }

    /**
     * Lifetime spend keyed by campaign id or ad set id.
     *
     * Insights spend is already in major currency units. date_preset=maximum
     * keeps a paused object's earlier spend. An id with no row is left out of
     * the map. That is not a spend of zero. A row whose spend is 0 is zero.
     *
     * @param  list<string>  $ids
     * @return array<string, float>
     */
    public function lifetimeSpend(string $parentId, string $level, ?string $adAccountId = null, array $ids = []): array
    {
        $idField = $level === 'adset' ? 'adset_id' : 'campaign_id';
        $rows = [];
        $after = null;

        do {
            $page = $this->get($parentId.'/insights', array_filter([
                'fields' => $idField.',spend',
                'level' => $level,
                'date_preset' => 'maximum',
                'limit' => 100,
                'filtering' => $ids === [] ? null : json_encode([[
                    'field' => $level === 'adset' ? 'adset.id' : 'campaign.id',
                    'operator' => 'IN',
                    'value' => array_values($ids),
                ]], JSON_THROW_ON_ERROR),
                'after' => $after,
            ], fn (mixed $value): bool => $value !== null && $value !== ''), $adAccountId, fresh: true);

            array_push($rows, ...($page['data'] ?? []));
            $after = data_get($page, 'paging.cursors.after');
        } while (is_string($after) && $after !== '' && count($rows) < 500);

        $spend = [];
        $parentKey = str_starts_with($parentId, 'act_') ? '' : (preg_replace('/\D/', '', $parentId) ?: '');

        foreach ($rows as $row) {
            if (! is_numeric($row['spend'] ?? null)) {
                continue;
            }

            $id = (string) ($row[$idField] ?? '');

            if ($id === '') {
                $id = $parentKey;
            }

            if ($id !== '') {
                $spend[$id] = (float) $row['spend'];
            }
        }

        return $spend;
    }

    /**
     * Whether one campaign, ad set, or ad exists yet.
     *
     * An MCP draft that is still publishing is not readable here. A null answer
     * means "not created yet", which is different from a live object whose
     * status happens to be paused.
     *
     * @return array{id: string, status: string, effective_status: string}|null
     */
    public function objectStatus(string $objectId, ?string $adAccountId = null): ?array
    {
        try {
            $object = $this->get($objectId, [
                'fields' => 'id,status,effective_status',
            ], $adAccountId, fresh: true);
        } catch (MetaException) {
            return null;
        }

        $status = (string) ($object['status'] ?? '');
        $effective = (string) ($object['effective_status'] ?? '');

        if (blank($object['id'] ?? null) || ($status === '' && $effective === '')) {
            return null;
        }

        return [
            'id' => (string) $object['id'],
            'status' => $status,
            'effective_status' => $effective,
        ];
    }

    /**
     * Which account a campaign belongs to, and nothing else about it.
     *
     * A campaign addressed by its own id cannot be checked against the allow
     * list before the request, because there is no account in the path to check.
     * That is unavoidable - but reading its budget, objective, schedule and bid
     * strategy on the way to finding out is not. This asks for the one field the
     * decision needs, so a campaign on an account we are not permitted to touch
     * never has its settings read, returned, or written into the call log.
     */
    public function campaignAccountId(string $campaignId): ?string
    {
        $accountId = $this->get($campaignId, ['fields' => 'account_id'])['account_id'] ?? null;

        return filled($accountId) ? (string) $accountId : null;
    }

    private const string AD_SET_DETAIL_FIELDS = 'effective_status,destination_type,attribution_spec,is_dynamic_creative,'
        .'pacing_type,bid_constraints,adset_schedule,frequency_control_specs,'
        .'daily_min_spend_target,daily_spend_cap,lifetime_min_spend_target,lifetime_spend_cap,'
        .'is_budget_schedule_enabled,budget_schedules.limit(101){id,budget_value,budget_value_type,time_start,time_end}';

    /**
     * The ad sets under a campaign.
     *
     * Budget, bidding, schedule and targeting live here rather than on the
     * campaign, so this is where everything we can edit actually is.
     *
     * $detailed adds delivery state and the settings Ads Manager shows that
     * nothing else here reads (destination, attribution, pacing, dayparting,
     * frequency caps, spend limits), for the campaign manager's mirror. Off by
     * default so every other caller keeps the response it was written for.
     *
     * @return list<array<string,mixed>>
     */
    public function adSets(string $campaignId, int $limit = 50, ?string $adAccountId = null, bool $fresh = false, bool $detailed = false): array
    {
        return $this->get($campaignId.'/adsets', [
            'fields' => 'id,name,status,daily_budget,lifetime_budget,bid_strategy,bid_amount,'
                .'billing_event,optimization_goal,start_time,end_time,targeting,promoted_object'
                .($detailed ? ','.self::AD_SET_DETAIL_FIELDS : ''),
            'limit' => $limit,
        ], $adAccountId, $fresh)['data'] ?? [];
    }

    /**
     * Whether this object has ever delivered, and how much it spent doing it.
     *
     * Works at any level - campaign, ad set or ad - because it omits the `level`
     * field that insights() pins to campaign.
     *
     * Exists because of 9 Oct. A campaign with 346.61 USD of spend and 66,652
     * impressions, still delivering, was deleted during a cleanup of test
     * campaigns, and Meta does not restore a deleted campaign - only its name
     * can be changed afterwards. Every other campaign in that sweep had zero
     * spend and zero impressions, so one read of this per object would have
     * stopped it outright. Nothing in the codebase asked, so nothing could.
     *
     * date_preset=maximum rather than a window, because the question is whether
     * this has *ever* run, not whether it ran recently.
     *
     * @return array{spend: float, impressions: int}
     */
    public function lifetimeDelivery(string $objectId, ?string $adAccountId = null): array
    {
        $rows = $this->get($objectId.'/insights', [
            'fields' => 'spend,impressions',
            'date_preset' => 'maximum',
        ], $adAccountId, fresh: true)['data'] ?? [];

        return [
            'spend' => (float) ($rows[0]['spend'] ?? 0),
            'impressions' => (int) ($rows[0]['impressions'] ?? 0),
        ];
    }

    /**
     * The ads under a campaign, or under one ad set.
     *
     * There was no ad reader at all. Graph could create an ad and delete one,
     * and nothing could list them - so for any campaign this product did not
     * build itself, the ads were unreachable: no ids, no names, no statuses.
     * CampaignImporter does not import ads either, so local rows are no help.
     * Anything that wants to act on a particular ad has to be able to name it
     * first, and nothing could.
     *
     * effective_status as well as status, because they answer different
     * questions: status is what somebody set on the ad, effective_status folds
     * in the ad set and campaign above it and the review state, which is why an
     * ad can read ACTIVE and still be showing nothing.
     *
     * adset_id is here so a flat list can be grouped without a call per ad.
     *
     * @return list<array<string,mixed>>
     */
    public function ads(string $parentId, int $limit = 50, ?string $adAccountId = null, bool $fresh = false, bool $withCopy = false): array
    {
        return $this->get($parentId.'/ads', [
            'fields' => 'id,name,status,effective_status,adset_id,created_time,updated_time,'
                .($withCopy ? $this->creativeCopyFields() : 'creative{id,name,title,body,thumbnail_url}'),
            'limit' => $limit,
        ], $adAccountId, $fresh)['data'] ?? [];
    }

    /**
     * One ad, including the creative fields that hold its copy.
     *
     * body and title are often empty. The words then live on object_story_spec
     * or asset_feed_spec, so both are read here.
     *
     * @return array<string, mixed>
     */
    public function ad(string $adId, ?string $adAccountId = null): array
    {
        return $this->get(trim($adId), [
            'fields' => 'name,status,effective_status,campaign_id,account_id,'.$this->creativeCopyFields(),
        ], $adAccountId, fresh: true);
    }

    /**
     * The creative fields that hold primary text, headline, description, and URL.
     *
     * body and title are often empty. The words and the link then live on the
     * story spec or the asset feed, so a read that stops at title cannot
     * answer a question about the rest of the ad.
     */
    private function creativeCopyFields(): string
    {
        return 'creative{id,body,title,call_to_action_type,object_story_spec,asset_feed_spec,link_url,object_url,url_tags,effective_object_story_id}';
    }

    /**
     * Ad sets with delivery and learning signals for performance ingest.
     *
     * @return list<array<string, mixed>>
     */
    public function performanceAdSets(string $campaignId, int $limit = 50, ?string $adAccountId = null): array
    {
        return $this->get($campaignId.'/adsets', [
            'fields' => 'id,name,status,effective_status,daily_budget,lifetime_budget,bid_strategy,'
                .'targeting,learning_stage_info,issues_info',
            'limit' => $limit,
        ], $adAccountId)['data'] ?? [];
    }

    /**
     * Performance for a live campaign.
     *
     * Insights, not the campaign object: spend and clicks live here. time_increment
     * of 1 yields one row per calendar day in the range.
     *
     * @return list<array<string, mixed>>
     */
    public function insights(string $campaignId, string $since, string $until, int|string $increment = 1, ?string $adAccountId = null): array
    {
        $rows = [];
        $after = null;

        do {
            $page = $this->get($campaignId.'/insights', array_filter([
                'fields' => 'campaign_id,spend,impressions,clicks,cpc,ctr,reach',
                'time_increment' => $increment,
                'time_range' => json_encode(['since' => $since, 'until' => $until]),
                'level' => 'campaign',
                'limit' => 100,
                'after' => $after,
            ], fn (mixed $value): bool => $value !== null && $value !== ''), $adAccountId);

            array_push($rows, ...($page['data'] ?? []));
            $after = data_get($page, 'paging.cursors.after');
        } while (is_string($after) && $after !== '' && count($rows) < 2000);

        return $rows;
    }

    /**
     * Hourly performance for a live campaign.
     *
     * Meta has no time_increment=hourly. Hour buckets come from the advertiser
     * timezone breakdown, one set of 24 hours per calendar day when combined
     * with time_increment=1. reach is omitted: hourly breakdowns reject it.
     *
     * @return list<array<string, mixed>>
     */
    public function insightsHourly(string $campaignId, string $since, string $until): array
    {
        $rows = [];
        $after = null;

        do {
            $page = $this->get($campaignId.'/insights', array_filter([
                'fields' => 'campaign_id,spend,impressions,clicks,cpc,ctr',
                'time_increment' => 1,
                'time_range' => json_encode(['since' => $since, 'until' => $until]),
                'breakdowns' => 'hourly_stats_aggregated_by_advertiser_time_zone',
                'level' => 'campaign',
                'limit' => 100,
                'after' => $after,
            ], fn (mixed $value): bool => $value !== null && $value !== ''));

            array_push($rows, ...($page['data'] ?? []));
            $after = data_get($page, 'paging.cursors.after');
        } while (is_string($after) && $after !== '' && count($rows) < 2000);

        return $rows;
    }

    /**
     * Ads Manager Breakdown → Platform: spend and results by publisher.
     *
     * @return list<array{
     *     publisher: string,
     *     spend: float,
     *     impressions: int,
     *     clicks: int,
     *     landing_page_views: float,
     *     cost_per_result: ?float
     * }>
     */
    public function publisherPlatformInsights(string $objectId, string $since, string $until, ?string $adAccountId = null): array
    {
        $objectId = trim($objectId);

        if ($objectId === '' || $this->token === '') {
            return [];
        }

        $page = $this->get($objectId.'/insights', [
            'fields' => 'spend,impressions,clicks,actions,cost_per_action_type',
            'breakdowns' => 'publisher_platform',
            'time_range' => json_encode(['since' => $since, 'until' => $until]),
        ], $adAccountId);

        $rows = [];

        foreach (is_array($page['data'] ?? null) ? $page['data'] : [] as $row) {
            if (! is_array($row)) {
                continue;
            }

            $publisher = strtolower(trim((string) ($row['publisher_platform'] ?? '')));

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

            $lpv = $this->actionValue($row['actions'] ?? null, ['omni_landing_page_view', 'landing_page_view']);
            $cpr = $this->actionValue($row['cost_per_action_type'] ?? null, ['omni_landing_page_view', 'landing_page_view']);
            $spend = is_numeric($row['spend'] ?? null) ? round((float) $row['spend'], 2) : 0.0;

            $rows[] = [
                'publisher' => $publisher,
                'spend' => $spend,
                'impressions' => is_numeric($row['impressions'] ?? null) ? (int) $row['impressions'] : 0,
                'clicks' => is_numeric($row['clicks'] ?? null) ? (int) $row['clicks'] : 0,
                'landing_page_views' => $lpv,
                'cost_per_result' => $cpr > 0 ? round($cpr, 2) : ($lpv > 0 ? round($spend / $lpv, 2) : null),
            ];
        }

        return $rows;
    }

    /**
     * @param  list<string>  $types
     */
    private function actionValue(mixed $actions, array $types): float
    {
        if (! is_array($actions)) {
            return 0.0;
        }

        $found = [];

        foreach ($actions as $action) {
            if (! is_array($action)) {
                continue;
            }

            $type = strtolower(trim((string) ($action['action_type'] ?? '')));

            if ($type !== '' && is_numeric($action['value'] ?? null)) {
                $found[$type] = (float) $action['value'];
            }
        }

        foreach ($types as $type) {
            if (isset($found[$type])) {
                return $found[$type];
            }
        }

        return 0.0;
    }

    /**
     * What a pixel has actually been firing, most frequent first.
     *
     * The ad set optimises toward one event, and until now that event was
     * inferred from the objective alone: leads meant LEAD whether or not the
     * pixel had ever seen a Lead. Kaushal's pixel 1017787001151608 fires
     * PageView and Subscribe and nothing else, and campaign 120252047635070626
     * is live asking Meta to optimise toward LEAD, which it can never observe.
     *
     * stats is bucketed hourly over the reporting window, so the counts are
     * summed per event name rather than read from one bucket. An empty result is
     * ordinary: a pixel installed an hour ago has no history, and that is not a
     * reason to refuse.
     *
     * The window and the pages both have to be asked for, and neither was.
     *
     * This called /stats with aggregation alone, so Meta applied its own default
     * window - about a day - and we read only the first page of it. Then we
     * reported the answer as though it covered the pixel's whole history. Pixel
     * 1337654058454168 has fired Lead 22 times and PageView 2,254 times over
     * thirty days; the bare call returns hourly buckets from the previous day and
     * PageView only. So the chat told buyers "this pixel has never fired Lead",
     * refused to optimise toward it, and sent them away to install an event that
     * was already live and working. Four turns of that on arb-dev on 8 Oct, and
     * the campaign then published on LEAD anyway through the objective's default.
     *
     * It also explains an earlier dead end I logged as unexplained: /stats
     * answering {"data":[]} for autoautomotive_clck while its last_fired_time was
     * two days old. The endpoint was fine. The query was a day wide.
     *
     * Thirty days because that is the window Events Manager shows by default, so
     * what the chat says about a pixel matches what the buyer sees when they go
     * and look. Longer would read better and cost more: every page is a call
     * against the hourly budget, and the budget's account-less bucket is shared
     * with the Page and ad-account lists that the launch flow needs.
     *
     * @return array<string,int> event name => times seen
     */
    public function pixelEvents(string $pixelId, int $days = 30): array
    {
        $totals = [];
        $after = null;
        $pages = 0;

        do {
            // Snapped to the hour, not to the second.
            //
            // CallLogger memoizes a read by its query, so a timestamp that moves
            // every second means two of these in one turn are two calls against
            // the budget where they used to be one - the exact cost this change
            // set out to reduce elsewhere. The buckets are hourly, so snapping
            // loses nothing, and the end is the close of the current hour rather
            // than its start so an event fired minutes ago still counts.
            $end = now()->startOfHour()->addHour();

            $response = $this->get($pixelId.'/stats', array_filter([
                'aggregation' => 'event',
                'start_time' => $end->copy()->subDays($days)->timestamp,
                'end_time' => $end->timestamp,
                'limit' => 500,
                'after' => $after,
            ], fn (mixed $value): bool => $value !== null && $value !== ''));

            foreach ($response['data'] ?? [] as $bucket) {
                foreach ($bucket['data'] ?? [] as $row) {
                    $name = (string) ($row['value'] ?? '');

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

                    $totals[$name] = ($totals[$name] ?? 0) + (int) ($row['count'] ?? 0);
                }
            }

            $after = data_get($response, 'paging.cursors.after');
            $pages++;
            // Hourly buckets over thirty days is 720 at most, so 500 to a page
            // needs two. The cap is a backstop against a cursor that never
            // settles, not an expected limit, and it is low because each page
            // spends the same shared budget as choose_page.
        } while (is_string($after) && $after !== '' && $pages < 4);

        arsort($totals);

        return $totals;
    }

    /**
     * Custom conversions on an ad account, optionally for one pixel.
     *
     * These are the saved rules behind "Create custom conversion", not the raw
     * event names in pixel stats. Archived rows and rows for another pixel are
     * left out. A failure here is the caller's to absorb: the event list can
     * still be built from pixel stats.
     *
     * @return list<array{id: string, name: string, custom_event_type: ?string, pixel_id: ?string, last_fired_time: ?string}>
     */
    public function customConversions(string $adAccountId, ?string $pixelId = null): array
    {
        $rows = [];
        $after = null;
        $pages = 0;
        $pixelId = $pixelId !== null ? trim($pixelId) : null;

        do {
            $response = $this->get($this->prefixed($adAccountId).'/customconversions', array_filter([
                'fields' => 'id,name,custom_event_type,pixel,is_archived,last_fired_time',
                'limit' => 100,
                'after' => $after,
            ], fn (mixed $value): bool => $value !== null && $value !== ''), $this->prefixed($adAccountId));

            foreach ($response['data'] ?? [] as $row) {
                if (! is_array($row) || ! empty($row['is_archived'])) {
                    continue;
                }

                $id = trim((string) ($row['id'] ?? ''));
                $name = trim((string) ($row['name'] ?? ''));
                $rowPixel = trim((string) data_get($row, 'pixel.id', ''));

                if ($id === '' || $name === '' || preg_match('/^[0-9]+$/', $id) !== 1) {
                    continue;
                }

                if ($pixelId !== null && $pixelId !== '' && $rowPixel !== $pixelId) {
                    continue;
                }

                $firedAt = $row['last_fired_time'] ?? null;

                $rows[] = [
                    'id' => $id,
                    'name' => $name,
                    'custom_event_type' => isset($row['custom_event_type']) ? (string) $row['custom_event_type'] : null,
                    'pixel_id' => $rowPixel !== '' ? $rowPixel : null,
                    'last_fired_time' => is_scalar($firedAt) && (string) $firedAt !== '' ? (string) $firedAt : null,
                ];
            }

            $after = data_get($response, 'paging.cursors.after');
            $pages++;
        } while (is_string($after) && $after !== '' && $pages < 4);

        return $rows;
    }

    /**
     * Pixels, called Datasets in Meta's current interface.
     *
     * An ad account's own edge returns only the pixels assigned to it, often a
     * single default. The one an advertiser actually means is frequently owned
     * by the parent business and shared, so both are returned and labelled.
     *
     * @return list<array<string,mixed>>
     */
    public function pixels(string $adAccountId, int $limit = 50, bool $fresh = false): array
    {
        $onAccount = collect($this->pixelList($this->prefixed($adAccountId).'/adspixels', [
            'fields' => 'id,name,last_fired_time',
            'limit' => $limit,
        ], $this->prefixed($adAccountId), $fresh))->map(fn (array $pixel): array => [...$pixel, 'owned_by' => 'ad account']);

        $businessId = data_get($this->adAccount($adAccountId, fresh: $fresh), 'business.id');

        if (! $businessId) {
            return $onAccount->all();
        }

        try {
            $owned = $this->pixelList($businessId.'/owned_pixels', ['fields' => 'id,name', 'limit' => $limit], $this->prefixed($adAccountId), $fresh);
        } catch (MetaException) {
            return $onAccount->all();   // the business read is a bonus, not a requirement
        }

        return $onAccount
            ->concat(collect($owned)
                ->reject(fn (array $pixel): bool => $onAccount->contains('id', $pixel['id']))
                ->map(fn (array $pixel): array => [...$pixel, 'owned_by' => 'business']))
            ->values()
            ->all();
    }

    /** @return list<array<string, mixed>> */
    private function pixelList(string $endpoint, array $query, string $adAccountId, bool $fresh): array
    {
        $pixels = [];
        $seen = [];

        for ($page = 0; $page < 20; $page++) {
            $response = $this->get($endpoint, $query, $adAccountId, $fresh);
            array_push($pixels, ...($response['data'] ?? []));
            $after = data_get($response, 'paging.cursors.after');

            if (blank(data_get($response, 'paging.next'))) {
                return $pixels;
            }

            if (! is_string($after) || $after === '') {
                throw new MetaException('Meta pixel pagination is missing its next cursor. The pixel list could not be fully verified.');
            }

            if (isset($seen[$after])) {
                throw new MetaException('Meta pixel pagination repeated a cursor. Try again before choosing or publishing.');
            }

            $seen[$after] = true;
            $query['after'] = $after;
        }

        throw new MetaException('Meta pixel discovery exceeded its page limit. The pixel list could not be fully verified.');
    }

    // ---------------------------------------------------------------- upload

    /** Uploads an image and returns the hash an ad creative references. */
    public function uploadImage(string $adAccountId, string $absolutePath, string $filename): string
    {
        $response = $this->multipart(
            $this->prefixed($adAccountId).'/adimages',
            'file',
            $absolutePath,
            $filename,
            timeout: 120,
        );

        // Meta keys the result by filename, which it may have normalised.
        $image = collect($response['images'] ?? [])->first();

        return $image['hash'] ?? throw new MetaException('Image upload returned no hash: '.json_encode($response));
    }

    /** Videos need processing time before an ad can use them. */
    public function uploadVideo(string $adAccountId, string $absolutePath, string $filename): string
    {
        $response = $this->multipart(
            $this->prefixed($adAccountId).'/advideos',
            'source',
            $absolutePath,
            $filename,
            timeout: 300,
        );

        return $response['id'] ?? throw new MetaException('Video upload returned no id: '.json_encode($response));
    }

    /**
     * Whether an uploaded video is ready to be put in an ad.
     *
     * Meta accepts the upload immediately and then transcodes, and an ad
     * created against a video still processing is rejected. The status is its
     * own read because the video edge does not return it alongside anything
     * else useful.
     *
     * Returns Meta's own word: ready, processing, or error.
     */
    public function videoStatus(string $videoId): string
    {
        return (string) (data_get($this->get($videoId, ['fields' => 'status']), 'status.video_status') ?: 'processing');
    }

    /**
     * A still from the video, which Meta requires on a video creative.
     *
     * Meta generates several once transcoding finishes and marks one preferred.
     * Taking the preferred one matches what the interface would have chosen,
     * and falling back to the first is better than refusing over a thumbnail.
     */
    public function videoThumbnail(string $videoId): ?string
    {
        $thumbnails = $this->get($videoId.'/thumbnails', ['fields' => 'uri,is_preferred'])['data'] ?? [];

        $preferred = collect($thumbnails)->firstWhere('is_preferred', true)
            ?? collect($thumbnails)->first();

        return $preferred['uri'] ?? null;
    }

    // ---------------------------------------------------------------- create

    public function createCampaign(CampaignSpec $spec, bool $dryRun = false): array
    {
        return $this->post($this->prefixed($spec->adAccountId).'/campaigns', array_filter([
            'name' => $spec->name,
            'objective' => $spec->objective,
            'status' => 'PAUSED',
            'buying_type' => 'AUCTION',
            // Was hardcoded empty, which declared every campaign as no special
            // category whether or not anyone had been asked.
            'special_ad_categories' => json_encode($spec->declaredCategories()),
            // Required whenever the budget sits on the ad set rather than the
            // campaign. Omitting it fails with subcode 4834011.
            'is_adset_budget_sharing_enabled' => $spec->budgetSharing(),
            ...$spec->budgetFields(),
            'execution_options' => $dryRun ? json_encode(['validate_only']) : null,
        ]), dryRun: $dryRun);
    }

    /**
     * @param  string  $status  PAUSED unless the caller is deliberately leaving
     *                          the ad set active beneath a paused campaign. The
     *                          default is the safe one, so a new caller that
     *                          says nothing creates nothing that can deliver.
     */
    public function createAdSet(AdSetSpec $spec, bool $dryRun = false, string $status = 'PAUSED'): array
    {
        return $this->post($this->prefixed($spec->adAccountId).'/adsets', array_filter([
            'name' => $spec->name,
            'campaign_id' => $spec->campaignId,
            ...$spec->budgetFields(),
            'billing_event' => 'IMPRESSIONS',
            'optimization_goal' => $spec->optimizationGoal,
            'targeting' => json_encode($spec->targetingSpec()),
            // Omitted rather than sent empty: Meta reads "[]" as a promoted
            // object it cannot make sense of, not as the absence of one.
            'promoted_object' => $spec->promotedObject() ? json_encode($spec->promotedObject()) : null,
            'status' => $status,
            ...$spec->schedule(),
            ...$spec->advertiserFields(),
            'execution_options' => $dryRun ? json_encode(['validate_only']) : null,
        ], fn (mixed $value): bool => $value !== null), dryRun: $dryRun);
    }

    /**
     * Point a live ad at a new creative that carries the requested wording.
     *
     * The ad must belong to the campaign the caller named. The story is the
     * one already on the creative, with the new lines written over it.
     *
     * @param  array<string, mixed>  $changes
     * @return array{creative_id: string, ad_id: string, campaign_id: string}
     */
    public function replaceAdCopy(string $adId, string $campaignId, ?string $fallbackAccount, array $changes): array
    {
        $ad = $this->ad($adId, $fallbackAccount);

        if ((string) ($ad['campaign_id'] ?? '') !== $campaignId) {
            throw new MetaException("Ad {$adId} is not in campaign {$campaignId}.");
        }

        $account = filled($ad['account_id'] ?? null)
            ? $this->prefixed((string) $ad['account_id'])
            : $this->prefixed((string) $fallbackAccount);
        $story = $ad['creative']['object_story_spec'] ?? null;

        if (! is_array($story) || $story === []) {
            throw new MetaException('That ad has no creative story to rewrite, so the copy was not changed.');
        }

        $created = $this->post($account.'/adcreatives', [
            'name' => 'Ad '.$adId.' copy',
            'object_story_spec' => json_encode($this->storyWithCopy($story, $changes)),
        ]);
        $creativeId = (string) ($created['id'] ?? '');

        if ($creativeId === '') {
            throw new MetaException('Meta did not return the new creative id.');
        }

        $this->updateEntity($adId, [
            'creative' => json_encode(['creative_id' => $creativeId]),
        ], $account);

        return [
            'creative_id' => $creativeId,
            'ad_id' => $adId,
            'campaign_id' => $campaignId,
        ];
    }

    /**
     * @param  array<string, mixed>  $story
     * @param  array<string, mixed>  $changes
     * @return array<string, mixed>
     */
    private function storyWithCopy(array $story, array $changes): array
    {
        foreach (['link_data', 'video_data', 'template_data'] as $key) {
            if (! is_array($story[$key] ?? null)) {
                continue;
            }

            if (filled($changes['primary_text'] ?? null)) {
                $story[$key]['message'] = (string) $changes['primary_text'];
            }

            if (filled($changes['headline'] ?? null)) {
                $story[$key][$key === 'video_data' ? 'title' : 'name'] = (string) $changes['headline'];
            }

            if (filled($changes['description'] ?? null)) {
                $description = (string) $changes['description'];
                $story[$key][$key === 'video_data' ? 'link_description' : 'description'] = $description;

                if ($key === 'video_data' && array_key_exists('description', $story[$key])) {
                    $story[$key]['description'] = $description;
                }
            }

            if (filled($changes['url'] ?? null)) {
                $url = $this->absoluteUrl((string) $changes['url']);

                if ($key !== 'video_data') {
                    $story[$key]['link'] = $url;
                }

                if (! is_array($story[$key]['call_to_action'] ?? null)) {
                    $story[$key]['call_to_action'] = ['type' => 'LEARN_MORE', 'value' => ['link' => $url]];
                } else {
                    $story[$key]['call_to_action']['value']['link'] = $url;
                }
            }

            if (filled($changes['cta'] ?? null)) {
                if (! is_array($story[$key]['call_to_action'] ?? null)) {
                    $story[$key]['call_to_action'] = ['type' => (string) $changes['cta']];
                } else {
                    $story[$key]['call_to_action']['type'] = (string) $changes['cta'];
                }
            }

            if (filled($story[$key]['image_hash'] ?? null) && filled($story[$key]['image_url'] ?? null)) {
                unset($story[$key]['image_url']);
            }
        }

        return $story;
    }

    private function absoluteUrl(string $url): string
    {
        $url = trim($url);

        if ($url === '' || preg_match('#^[a-z][a-z0-9+.-]*://#i', $url) === 1) {
            return $url;
        }

        return 'https://'.$url;
    }

    public function createCreative(CreativeSpec $spec): array
    {
        // No degrees_of_freedom_spec: Meta deprecated the standard enhancements
        // opt-out (subcode 3858504) and now wants individual features named.
        return $this->post($this->prefixed($spec->adAccountId).'/adcreatives', [
            'name' => $spec->name,
            'object_story_spec' => json_encode($spec->storySpec()),
            // Beside the story spec, not inside it.
            ...$spec->instagramFields(),
        ]);
    }

    /**
     * Copy a campaign on its own, without its ad sets.
     *
     * Meta copies at most three children in one call, so the ad sets are
     * copied into it one at a time afterwards.
     *
     * @param  string  $status  Meta's status_option: ACTIVE, PAUSED or INHERITED_FROM_SOURCE
     * @return array<string, mixed>
     */
    public function copyCampaign(string $campaignId, ?string $adAccountId = null, string $status = 'PAUSED'): array
    {
        $copied = $this->post(trim($campaignId).'/copies', [
            'deep_copy' => 'false',
            'status_option' => $status,
            'rename_options' => json_encode([
                'rename_strategy' => 'ONLY_TOP_LEVEL_RENAME',
                'rename_suffix' => ' - copy',
            ]),
        ], adAccountId: filled($adAccountId) ? $this->prefixed($adAccountId) : null);
        $copied['status_option'] = $status;

        return $copied;
    }

    /**
     * Copy an ad set inside a campaign, ads included.
     *
     * deep_copy brings the ads. Meta keeps the targeting, so a city, a gender
     * and an interest do not have to be rebuilt here. status_option PAUSED
     * means the copy cannot spend until someone starts it; the chat's copies
     * go out ACTIVE, the campaign manager's PAUSED.
     *
     * @param  string  $status  Meta's status_option: ACTIVE, PAUSED or INHERITED_FROM_SOURCE
     * @param  bool  $deep  false copies the ad set alone, for one with more ads than a single call copies
     * @return array<string, mixed>
     */
    public function copyAdSet(string $adSetId, string $campaignId, ?string $adAccountId = null, string $status = 'ACTIVE', bool $deep = true): array
    {
        $copied = $this->post(trim($adSetId).'/copies', [
            'campaign_id' => $campaignId,
            'deep_copy' => $deep ? 'true' : 'false',
            'status_option' => $status,
            'rename_options' => json_encode([
                'rename_strategy' => 'DEEP_RENAME',
                'rename_suffix' => ' - copy',
            ]),
        ], adAccountId: filled($adAccountId) ? $this->prefixed($adAccountId) : null);
        $copied['status_option'] = $status;

        return $copied;
    }

    /**
     * The live ad set, including the targeting Meta is already delivering.
     *
     * @return array<string, mixed>
     */
    public function readAdSet(string $adSetId, ?string $adAccountId = null): array
    {
        return $this->get(trim($adSetId), [
            'fields' => 'id,name,targeting,billing_event,optimization_goal,bid_strategy,bid_amount,'
                .'bid_constraints,pacing_type,daily_budget,lifetime_budget,promoted_object,destination_type,'
                .'start_time,end_time,adset_schedule,attribution_spec,is_dynamic_creative',
        ], $adAccountId, true);
    }

    /** @return array<string, mixed> */
    public function readAdSetForEventCopy(string $adSetId, string $account): array
    {
        return $this->get(trim($adSetId), [
            'fields' => 'id,account_id,campaign_id,name,targeting,billing_event,optimization_goal,bid_strategy,bid_amount,'
                .'daily_budget,lifetime_budget,promoted_object,start_time,end_time,'.self::AD_SET_DETAIL_FIELDS,
        ], $account, true);
    }

    /**
     * A paused ad set in the same campaign, using the live targeting and a pixel this account can use.
     *
     * The copies endpoint refuses when the source pixel is not on the ad account, and it has no
     * way to swap that pixel. Reading the ad set and creating the copy keeps the city, gender
     * and interests Meta already has, with the pixel the user chose.
     *
     * @param  array<string, mixed>  $source
     * @return array<string, mixed>
     */
    public function createAdSetCopy(string $adAccountId, string $campaignId, array $source, string $pixelId, ?string $name = null, ?string $conversionEvent = null): array
    {
        $promoted = (array) ($source['promoted_object'] ?? []);
        unset($promoted['custom_conversion_id'], $promoted['pixel_rule']);
        $promoted['pixel_id'] = $pixelId;
        $extra = [];
        if ($conversionEvent !== null) {
            unset($promoted['custom_event_str']);
            $promoted['custom_event_type'] = $conversionEvent;
            foreach (['pacing_type', 'bid_constraints', 'adset_schedule', 'frequency_control_specs', 'attribution_spec'] as $field) {
                if (! empty($source[$field])) {
                    $extra[$field] = json_encode($source[$field], JSON_THROW_ON_ERROR);
                }
            }
            foreach (['is_dynamic_creative', 'daily_min_spend_target', 'daily_spend_cap', 'lifetime_min_spend_target', 'lifetime_spend_cap'] as $field) {
                if (isset($source[$field])) {
                    $extra[$field] = $source[$field];
                }
            }
        }

        $hasBudget = (int) ($source['daily_budget'] ?? 0) > 0 || (int) ($source['lifetime_budget'] ?? 0) > 0;

        return $this->post($this->prefixed($adAccountId).'/adsets', array_filter([
            'name' => filled($name) ? $name : trim((string) ($source['name'] ?? 'Ad set')).' - copy',
            'campaign_id' => $campaignId,
            'billing_event' => $source['billing_event'] ?? 'IMPRESSIONS',
            'optimization_goal' => $source['optimization_goal'] ?? null,
            'bid_strategy' => $hasBudget ? ($source['bid_strategy'] ?? null) : null,
            'bid_amount' => $hasBudget ? ($source['bid_amount'] ?? null) : null,
            'daily_budget' => (int) ($source['daily_budget'] ?? 0) > 0 ? $source['daily_budget'] : null,
            'lifetime_budget' => (int) ($source['lifetime_budget'] ?? 0) > 0 ? $source['lifetime_budget'] : null,
            'targeting' => json_encode($source['targeting'] ?? []),
            'promoted_object' => json_encode($promoted),
            'destination_type' => $source['destination_type'] ?? null,
            'start_time' => $this->futureTime($source['start_time'] ?? null),
            'end_time' => $this->futureTime($source['end_time'] ?? null),
            'status' => 'PAUSED',
            ...$extra,
        ], fn (mixed $value): bool => $value !== null && $value !== ''));
    }

    /**
     * Copy one ad into an ad set.
     *
     * @param  string  $status  Meta's status_option: ACTIVE, PAUSED or INHERITED_FROM_SOURCE
     */
    public function copyAd(string $adId, string $adSetId, ?string $adAccountId = null, string $status = 'ACTIVE'): array
    {
        $copied = $this->post(trim($adId).'/copies', [
            'adset_id' => $adSetId,
            'status_option' => $status,
            'rename_options' => json_encode([
                'rename_strategy' => 'DEEP_RENAME',
                'rename_suffix' => ' - copy',
            ]),
        ], adAccountId: filled($adAccountId) ? $this->prefixed($adAccountId) : null);
        $copied['status_option'] = $status;

        return $copied;
    }

    private function futureTime(mixed $time): ?string
    {
        if (! is_string($time) || trim($time) === '') {
            return null;
        }

        try {
            $parsed = Carbon::parse($time);
        } catch (\Throwable) {
            return null;
        }

        return $parsed->isFuture() ? $parsed->toIso8601String() : null;
    }

    public function createAd(string $adAccountId, string $adSetId, string $creativeId, string $name, string $status = 'PAUSED'): array
    {
        return $this->post($this->prefixed($adAccountId).'/ads', [
            'name' => $name,
            'adset_id' => $adSetId,
            'creative' => json_encode(['creative_id' => $creativeId]),
            'status' => $status,
        ]);
    }

    /**
     * Change fields on an existing object.
     *
     * @param  array<string,mixed>  $fields
     */
    public function updateEntity(string $objectId, array $fields, ?string $adAccountId = null): array
    {
        try {
            return $this->log->record(
                new CallContext(
                    'graph', 'POST', $objectId, $adAccountId, $fields,
                    mutating: true,
                    quotaScope: hash('sha256', $this->token),
                ),
                fn (): array => $this->withFallback(fn (string $token): array => $this->unwrap(
                    Http::timeout(60)->asForm()->post($this->url($objectId), [...$fields, 'access_token' => $token]),
                    $objectId,
                )),
            );
        } finally {
            $this->invalidateResourceDiscovery();
        }
    }

    /**
     * Deletion deliberately skips the allow list. If we created something, we
     * must always be able to remove it, even after the configuration changes.
     */
    public function delete(string $objectId): bool
    {
        try {
            $response = $this->log
                ->record(
                    // Exempt from both checks, and deliberately.
                    //
                    // The kill switch is paused-writes, and a rollback has to be
                    // able to finish while writes are paused or a half-made
                    // campaign stays half-made. The allow list is exempt for a
                    // different reason: deleting is the safe direction. Refusing to
                    // remove an object because its account was revoked after we
                    // created it would strand a paid object with no way to clean it
                    // up, which is worse than the read it protects against.
                    new CallContext('graph', 'DELETE', $objectId, mutating: true, guarded: false, accountChecked: false),
                    fn (): array => $this->withFallback(fn (string $token): array => $this->unwrap(
                        Http::timeout(60)->delete($this->url($objectId), ['access_token' => $token]),
                        $objectId,
                    )),
                );

            return (bool) ($response['success'] ?? false);
        } finally {
            $this->invalidateResourceDiscovery();
        }
    }

    /** @param array<string, int|string> $fields */
    public function createBudgetSchedule(string $adSetId, string $adAccountId, array $fields): string
    {
        $created = $this->post($adSetId.'/budget_schedules', $fields, adAccountId: $adAccountId);
        $id = (string) ($created['id'] ?? '');
        if ($id === '' || ! ctype_digit($id)) {
            throw new \RuntimeException('Meta accepted the budget boost but returned no schedule ID. Refresh before trying again.');
        }

        return $id;
    }

    // ------------------------------------------------------------- internals

    private function discoveryCacheSeconds(string $endpoint, array $query): int
    {
        $setting = match (true) {
            preg_match('~^act_[0-9]+/targetingsearch$~D', $endpoint) === 1 => ($query['limit_type'] ?? 'interests') === 'interests' ? 'interests' : 'targeting_catalog',
            preg_match('~^act_[0-9]+/targetingsuggestions$~D', $endpoint) === 1 => 'targeting_catalog',
            preg_match('~^act_[0-9]+/targetingbrowse$~D', $endpoint) === 1
                || ($endpoint === 'search' && ($query['type'] ?? null) === 'adTargetingCategory') => 'targeting_catalog',
            in_array($endpoint, ['me/adaccounts', 'me/accounts'], true) => 'accounts_and_pages',
            $this->discoveryGroup($endpoint) !== null => 'pixels_and_audiences',
            default => null,
        };

        return $setting === null ? 0 : max(0, (int) config('platforms.meta.discovery_cache.'.$setting, 0));
    }

    private function discoveryGroup(string $endpoint): ?string
    {
        return match (true) {
            preg_match('~^(act_[0-9]+/adspixels|[0-9]+/owned_pixels)$~D', $endpoint) === 1 => 'meta-pixels',
            preg_match('~^act_[0-9]+/customaudiences$~D', $endpoint) === 1 => 'meta-audiences',
            default => null,
        };
    }

    private function invalidateResourceDiscovery(?string $group = null): void
    {
        foreach ($group === null ? ['meta-pixels', 'meta-audiences'] : [$group] as $resource) {
            $this->log->invalidateDiscovery(hash('sha256', $this->version.'|'.$this->token), $resource);
        }
    }

    /**
     * @param  ?string  $adAccountId  the account this read belongs to, when the
     *                                endpoint does not name it
     */
    private function get(string $endpoint, array $query = [], ?string $adAccountId = null, bool $fresh = false): array
    {
        return $this->log->record(
            // accountIn() only finds an account when the endpoint starts with
            // one, so every read addressed by object id - a campaign, an ad
            // set, insights - reached the API with no account and skipped the
            // allow list entirely. assertAccountAllowed()'s own docblock says
            // reads are included, "an account we may not spend on is an account
            // we have no business reading either", and they were not.
            new CallContext(
                'graph', 'GET', $endpoint, $adAccountId ?? $this->accountIn($endpoint), $query,
                memoize: ! $fresh,
                credentialScope: hash('sha256', $this->version.'|'.$this->token),
                cacheSeconds: $fresh ? 0 : $this->discoveryCacheSeconds($endpoint, $query),
                quotaScope: hash('sha256', $this->token),
                discoveryGroup: $this->discoveryGroup($endpoint),
            ),
            fn (): array => $this->withFallback(fn (string $token): array => $this->unwrap(
                Http::timeout(60)->get($this->url($endpoint), [...$query, 'access_token' => $token]),
                $endpoint,
            )),
        );
    }

    /**
     * Create a pixel on an ad account.
     *
     * Meta renamed these to "datasets" in Events Manager and left the API
     * alone, so the buyer may well ask for a dataset and mean this exactly.
     * There is no /owned_data_sets path; adspixels is still the only one.
     *
     * Created on the ad account rather than the business. Both endpoints
     * accept, but the account is the thing in hand and the one the campaign
     * already publishes to; a business-owned pixel is the wider choice and
     * wants a deliberate decision rather than a default.
     *
     * @return array<string, mixed>
     */
    public function createPixel(string $adAccountId, string $name): array
    {
        return $this->post($this->prefixed($adAccountId).'/adspixels', ['name' => $name]);
    }

    private function post(string $endpoint, array $form, bool $dryRun = false, ?string $adAccountId = null): array
    {
        try {
            return $this->log->record(
                new CallContext(
                    'graph', 'POST', $endpoint, $adAccountId ?? $this->accountIn($endpoint), $form,
                    mutating: ! $dryRun, dryRun: $dryRun,
                    credentialScope: hash('sha256', $this->version.'|'.$this->token),
                    quotaScope: hash('sha256', $this->token),
                ),
                fn (): array => $this->withFallback(fn (string $token): array => $this->unwrap(
                    Http::timeout(120)->asForm()->post($this->url($endpoint), [...$form, 'access_token' => $token]),
                    $endpoint,
                )),
            );
        } finally {
            if (! $dryRun && ($group = $this->discoveryGroup($endpoint)) !== null) {
                $this->invalidateResourceDiscovery($group);
            }
        }
    }

    /**
     * The file is checked before anything reads it.
     *
     * Both filesize() below and file_get_contents() in the closure raise a PHP
     * warning on a missing file, which becomes an ErrorException carrying the
     * absolute server path. That reached the buyer verbatim in the chat as
     * "filesize(): stat failed for /var/www/php85/...", which tells them
     * nothing they can act on and discloses the filesystem layout.
     */
    private function multipart(string $endpoint, string $field, string $path, string $filename, int $timeout): array
    {
        if (! is_file($path)) {
            throw new MetaException("The file for {$filename} is missing, so it could not be uploaded.");
        }

        return $this->log->record(
            new CallContext(
                'graph', 'POST', $endpoint, $this->accountIn($endpoint), ['file' => $filename, 'bytes' => filesize($path)],
                mutating: true,
                credentialScope: hash('sha256', $this->version.'|'.$this->token),
                quotaScope: hash('sha256', $this->token),
            ),
            fn (): array => $this->withFallback(fn (string $token): array => $this->unwrap(
                Http::timeout($timeout)
                    ->asMultipart()
                    ->attach($field, file_get_contents($path), $filename)
                    ->post($this->url($endpoint), ['access_token' => $token]),
                $endpoint,
            )),
        );
    }

    /**
     * One retry with the fallback token when Meta rate-limits the primary token.
     *
     * The hourly limits are not retried on the same token, because that spends
     * the quota again for the same refusal. A different token is a different
     * quota. No fallback configured leaves the original error unchanged.
     *
     * @param  callable(string): array<string, mixed>  $send
     * @return array<string, mixed>
     */
    private function withFallback(callable $send): array
    {
        try {
            return $send($this->token);
        } catch (MetaException $exception) {
            if (! $this->canUseFallback($exception)) {
                throw $exception;
            }

            Log::warning('Meta rate-limited the request; retrying with the fallback token', [
                'code' => $exception->getCode(),
            ]);

            return $send($this->fallbackToken);
        }
    }

    private function canUseFallback(MetaException $exception): bool
    {
        if ($this->fallbackToken === '' || $this->fallbackToken === $this->token) {
            return false;
        }

        return in_array($exception->getCode(), [4, 17, 32, 613, 80004], true);
    }

    /**
     * Meta buries the useful sentence in error_user_msg and leaves `message` as
     * "Invalid parameter". Lead with the one a human can act on.
     */
    private function unwrap(Response $response, string $endpoint): array
    {
        $usage = $this->usageDiagnostics($response, $endpoint);
        $body = $response->json();

        if (! is_array($body)) {
            throw new MetaException("Non-JSON response from {$endpoint}");
        }

        if ($error = $body['error'] ?? null) {
            $message = sprintf(
                '%s [%s %s%s] on %s',
                rtrim(trim($error['error_user_msg'] ?? $error['error_user_title'] ?? $error['message'] ?? 'unknown error'), '.'),
                $error['type'] ?? '?',
                $error['code'] ?? '?',
                isset($error['error_subcode']) ? '/'.$error['error_subcode'] : '',
                $endpoint,
            );

            // Said in front of Meta's own sentence, not instead of it.
            //
            // Graph's wording for a dead token is "An active access token must be
            // used to query information about the current user", which names
            // neither the cause nor the cure, and the chat filled the gap by
            // calling it a rate limit and advising the user to wait. Meta's text
            // stays because it is the thing worth quoting to Meta; what goes in
            // front is whether waiting can possibly help.
            $reason = MetaApiError::permanentReason($error['code'] ?? null, $error['error_subcode'] ?? null);

            throw new MetaException(
                $reason === null ? $message : $reason.' '.$message,
                code: (int) ($error['code'] ?? 0),
                diagnostics: [
                    'meta_error_subcode' => (int) ($error['error_subcode'] ?? 0),
                    'http_status' => $response->status(),
                    ...($usage === [] ? [] : ['meta_usage' => $usage]),
                ],
            );
        }

        return $body;
    }

    /** @return array<string, mixed> */
    private function usageDiagnostics(Response $response, string $endpoint): array
    {
        $usage = [];

        foreach (['X-App-Usage', 'X-Ad-Account-Usage', 'X-Business-Use-Case-Usage'] as $header) {
            $raw = $response->header($header);

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

            $decoded = strlen($raw) <= 16384 ? json_decode($raw, true) : null;

            if (! is_array($decoded)) {
                Log::warning('Meta usage header is invalid', ['header' => $header, 'endpoint' => $endpoint]);

                continue;
            }

            $metrics = $this->usageMetrics($decoded);

            if ($metrics !== []) {
                $usage[strtolower($header)] = $metrics;
            }
        }

        $retryAfter = $response->header('Retry-After');

        if ($retryAfter !== '') {
            $seconds = ctype_digit($retryAfter) ? (int) $retryAfter : false;

            if ($seconds === false && ($date = strtotime($retryAfter)) !== false) {
                $seconds = max(0, $date - now()->timestamp);
            }

            if ($seconds !== false) {
                $usage['retry_after_seconds'] = $seconds;
            } else {
                Log::warning('Meta recovery header is invalid', ['endpoint' => $endpoint]);
            }
        }

        if ($usage !== []) {
            Log::info('Meta Graph quota usage', [
                'endpoint' => $endpoint,
                'credential_scope' => hash('sha256', $this->version.'|'.$this->token),
                'http_status' => $response->status(),
                'usage' => $usage,
            ]);
        }

        return $usage;
    }

    /**
     * Only provider-defined numeric quota fields may enter telemetry.
     *
     * @param  array<string|int, mixed>  $values
     * @return array<string|int, mixed>
     */
    private function usageMetrics(array $values, int $depth = 0): array
    {
        $metrics = [];

        if ($depth > 3) {
            return [];
        }

        foreach (array_slice($values, 0, 50, true) as $key => $value) {
            if (is_array($value) && ctype_digit((string) $key)) {
                $nested = $this->usageMetrics($value, $depth + 1);

                if ($nested !== []) {
                    $metrics[$key] = $nested;
                }
            } elseif (in_array($key, [
                'call_count', 'total_cputime', 'total_time', 'acc_id_util_pct',
                'reset_time_duration', 'estimated_time_to_regain_access',
            ], true) && is_numeric($value) && (float) $value >= 0 && is_finite((float) $value)) {
                $metrics[$key] = (float) $value;
            }
        }

        return $metrics;
    }

    private function url(string $endpoint): string
    {
        return "https://graph.facebook.com/{$this->version}/{$endpoint}";
    }

    private function prefixed(string $adAccountId): string
    {
        return str_starts_with($adAccountId, 'act_') ? $adAccountId : 'act_'.$adAccountId;
    }

    private function accountIn(string $endpoint): ?string
    {
        return preg_match('/^(act_\d+)/', $endpoint, $matches) ? $matches[1] : null;
    }
}
