<?php

namespace App\Services\Meta;

use App\Campaigns\Publishing\MetaDraftPause;
use App\Services\Platforms\Support\CallLogger;
use App\Support\PublicHttp;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Sleep;
use Throwable;

/**
 * The one thing the rest of the application talks to.
 *
 * Chooses a transport per operation: the Ads MCP for creation when it is
 * enabled, the Graph API for uploads and deletion, which the MCP cannot do.
 * Callers never need to know which ran; the audit log records it either way.
 */
class Meta
{
    /**
     * Sales campaigns are created on Graph for the rest of this request.
     *
     * ads_create_campaign has no argument that refuses a catalogue, and it
     * attaches the business catalogue to a Sales campaign. Graph is given no
     * catalogue data, so Advantage+ catalogue stays off. The ad set, creative
     * and ad that follow have to use the same transport: an MCP draft cannot
     * sit under a campaign Graph already created.
     */
    private bool $salesOnGraph = false;

    public function __construct(
        private readonly GraphApi $graph,
        private readonly ?AdsMcp $mcp,
        private readonly CallLogger $log,
    ) {}

    /** Attribute everything that follows to a draft, for the audit trail. */
    public function on(?int $campaignId, ?string $actor): static
    {
        $this->log->attributeTo($campaignId, $actor);

        return $this;
    }

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

    public function adAccounts(): array
    {
        return $this->graph->adAccounts();
    }

    public function adAccount(string $adAccountId, bool $fresh = false): array
    {
        return $this->graph->adAccount($adAccountId, $fresh);
    }

    /**
     * Verified advertiser names this ad account can put on an ad set.
     *
     * @return list<string>
     */
    public function verifiedAdvertisers(string $adAccountId): array
    {
        return $this->graph->verifiedAdvertisers($adAccountId);
    }

    /**
     * Verified advertiser ids already saved on this account's ad sets.
     *
     * @return list<array{beneficiary_id: string, payer_id: string, beneficiary_name: string, payer_name: string, categories: list<string>}>
     */
    public function verifiedAdvertiserIdentities(string $adAccountId): array
    {
        return $this->graph->verifiedAdvertiserIdentities($adAccountId);
    }

    public function marketAudienceEstimate(string $adAccountId, string $marketKey): int
    {
        return $this->graph->marketAudienceEstimate($adAccountId, $marketKey);
    }

    /** @return list<array<string, mixed>> */
    public function customAudiences(string $adAccountId, bool $fresh = false): array
    {
        return $this->graph->customAudiences($adAccountId, $fresh);
    }

    /** @return list<array<string, mixed>> */
    public function targetingInterests(string $adAccountId, string $query): array
    {
        return $this->graph->targetingInterests($adAccountId, $query);
    }

    /** @param list<string> $ids
     * @return list<array<string, mixed>>
     */
    public function validateTargetingInterests(string $adAccountId, array $ids): array
    {
        return $this->graph->validateTargetingInterests($adAccountId, $ids);
    }

    /** @return list<array<string, mixed>> */
    public function targetingSearch(string $adAccountId, string $query, string $limitType): array
    {
        return $this->graph->targetingSearch($adAccountId, $query, $limitType);
    }

    /** @return list<array<string, mixed>> */
    public function targetingBrowse(string $adAccountId, string $limitType): array
    {
        return $this->graph->targetingBrowse($adAccountId, $limitType);
    }

    /**
     * @param  list<array{type: string, id: string}>  $targetingList
     * @return list<array<string, mixed>>
     */
    public function targetingSuggestions(string $adAccountId, array $targetingList): array
    {
        return $this->graph->targetingSuggestions($adAccountId, $targetingList);
    }

    /**
     * @param  array<string, mixed>  $targetingSpec
     * @return array<string, mixed>
     */
    public function deliveryEstimate(string $adAccountId, string $optimizationGoal, array $targetingSpec): array
    {
        return $this->graph->deliveryEstimate($adAccountId, $optimizationGoal, $targetingSpec);
    }

    /**
     * @param  list<string>  $ids
     * @return list<array<string, mixed>>
     */
    public function validateTargetingOptions(string $adAccountId, string $type, array $ids): array
    {
        return $this->graph->validateTargetingOptions($adAccountId, $type, $ids);
    }

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

    public function pages(bool $fresh = false): array
    {
        return $this->graph->pages(fresh: $fresh);
    }

    public function createPixel(string $adAccountId, string $name): array
    {
        return $this->graph->createPixel($adAccountId, $name);
    }

    public function pixels(string $adAccountId, bool $fresh = false): array
    {
        return $this->graph->pixels($adAccountId, fresh: $fresh);
    }

    /** @return array<string,int> event name => times seen, most frequent first */
    public function pixelEvents(string $pixelId): array
    {
        return $this->graph->pixelEvents($pixelId);
    }

    /**
     * @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
    {
        return $this->graph->customConversions($adAccountId, $pixelId);
    }

    /** @return list<array{id: string, username: string|null, source: string}> */
    public function instagramAccounts(string $adAccountId, ?string $pageId = null): array
    {
        return $this->graph->instagramAccounts($adAccountId, $pageId);
    }

    /**
     * Campaigns already on the account, ours or anyone else's.
     *
     * Graph, not the MCP. The MCP formats values for reading, so a budget comes
     * back as "$25.00 USD" and a bid strategy as "Cost per result goal", and
     * neither can be diffed against a new value or written back.
     *
     * @return list<array<string,mixed>>
     */
    public function campaigns(string $adAccountId): array
    {
        return $this->graph->campaigns($adAccountId);
    }

    /**
     * @param  ?string  $adAccountId  the account this campaign belongs to, when
     *                                the caller already knows it, so the read
     *                                is checked against the allow list
     */
    public function campaign(string $campaignId, ?string $adAccountId = null, bool $fresh = false): array
    {
        return $this->graph->campaign($campaignId, $adAccountId, $fresh);
    }

    /**
     * One live ad set, as Meta is delivering it.
     *
     * @return array<string, mixed>
     */
    public function readAdSet(string $adSetId, ?string $adAccountId = null): array
    {
        return $this->graph->readAdSet($adSetId, $adAccountId);
    }

    /**
     * Languages Meta can target. Only for changing the language on a live ad set.
     *
     * @return list<array{locale: int, name: string}>
     */
    public function adLocales(string $adAccountId, string $query): array
    {
        return $this->graph->adLocales($query, $adAccountId);
    }

    /**
     * Interests for a live ad set search. Not used while creating a campaign.
     *
     * @return list<array{id: string, name: string, audience_size: int}>
     */
    public function adInterests(string $adAccountId, string $query): array
    {
        return $this->graph->adInterests($adAccountId, $query);
    }

    /**
     * @return list<array{id: string, name: string, audience_size: int}>
     */
    public function adWorkPositions(string $adAccountId, string $query): array
    {
        return $this->graph->adWorkPositions($adAccountId, $query);
    }

    /**
     * @param  list<string>  $names
     * @return list<array{id: string, name: string, audience_size: int}>
     */
    public function adInterestSuggestions(string $adAccountId, array $names): array
    {
        return $this->graph->adInterestSuggestions($adAccountId, $names);
    }

    /**
     * Active and paused campaigns, with budget and bid strategy still in minor units.
     *
     * @return list<array<string, mixed>>
     */
    public function deliveryCampaigns(string $adAccountId, int $limit = 26): array
    {
        return $this->graph->deliveryCampaigns($adAccountId, $limit);
    }

    /**
     * Ad sets under one campaign, with budget, bid, and spend limits in minor units.
     *
     * @return list<array<string, mixed>>
     */
    public function deliveryAdSets(string $campaignId, ?string $adAccountId = null, int $limit = 50): array
    {
        return $this->graph->deliveryAdSets($campaignId, $adAccountId, $limit);
    }

    /**
     * Lifetime spend in major units, keyed by campaign id or ad set id.
     *
     * @param  list<string>  $ids
     * @return array<string, float>
     */
    public function lifetimeSpend(string $parentId, string $level, ?string $adAccountId = null, array $ids = []): array
    {
        return $this->graph->lifetimeSpend($parentId, $level, $adAccountId, $ids);
    }

    /** Which account a campaign is on, without reading the campaign itself. */
    public function campaignAccountId(string $campaignId): ?string
    {
        return $this->graph->campaignAccountId($campaignId);
    }

    /** @return list<array<string,mixed>> */
    public function adSets(string $campaignId, ?string $adAccountId = null, bool $fresh = false, bool $detailed = false): array
    {
        return $this->graph->adSets($campaignId, 50, $adAccountId, $fresh, $detailed);
    }

    /**
     * Whether an object has ever delivered. Any level.
     *
     * @return array{spend: float, impressions: int}
     */
    public function lifetimeDelivery(string $objectId, ?string $adAccountId = null): array
    {
        return $this->graph->lifetimeDelivery($objectId, $adAccountId);
    }

    /**
     * The ads under a campaign, or under one ad set.
     *
     * @return list<array<string,mixed>>
     */
    public function ads(string $parentId, ?string $adAccountId = null, bool $fresh = false, bool $withCopy = false): array
    {
        return $this->graph->ads($parentId, 50, $adAccountId, $fresh, $withCopy);
    }

    /**
     * Primary text, headline, description, and URL of one live ad.
     *
     * @return array{name: string, status: string, effective_status: string, campaign_id: string, primary_text: string, headline: string, description: string, url: string}
     */
    public function adCopy(string $adId, ?string $adAccountId = null): array
    {
        return (new AdCreativeCopy)->fromAd($this->graph->ad($adId, $adAccountId));
    }

    /**
     * New wording on a live ad, without a local row.
     *
     * @param  array<string, mixed>  $changes
     * @return array{creative_id: string, ad_id: string, campaign_id: string}
     */
    public function replaceAdCopy(string $adId, string $campaignId, ?string $adAccountId, array $changes): array
    {
        return $this->graph->replaceAdCopy($adId, $campaignId, $adAccountId, $changes);
    }

    /** @return list<array<string,mixed>> */
    public function performanceAdSets(string $campaignId, ?string $adAccountId = null): array
    {
        return $this->graph->performanceAdSets($campaignId, 50, $adAccountId);
    }

    /** @return list<array<string, mixed>> */
    public function insights(string $campaignId, string $since, string $until, int|string $increment = 1, ?string $adAccountId = null): array
    {
        return $this->graph->insights($campaignId, $since, $until, $increment, $adAccountId);
    }

    /** @return list<array<string, mixed>> */
    public function insightsHourly(string $campaignId, string $since, string $until): array
    {
        return $this->graph->insightsHourly($campaignId, $since, $until);
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function publisherPlatformInsights(string $objectId, string $since, string $until, ?string $adAccountId = null): array
    {
        return $this->graph->publisherPlatformInsights($objectId, $since, $until, $adAccountId);
    }

    public function uploadImage(string $adAccountId, string $path, string $filename): string
    {
        return $this->graph->uploadImage($adAccountId, $path, $filename);
    }

    public function uploadVideo(string $adAccountId, string $path, string $filename): string
    {
        return $this->graph->uploadVideo($adAccountId, $path, $filename);
    }

    /**
     * Block until Meta has finished transcoding a video, or give up saying so.
     *
     * Meta accepts an upload immediately and transcodes afterwards, and an ad
     * built against a video that is still processing is rejected. Publishing is
     * synchronous from the chat, so this waits rather than scheduling: a short
     * bounded wait, because most creatives are a few seconds of video and the
     * person is watching a spinner.
     *
     * Giving up is not a failure of the creative. It is worth saying plainly so
     * they try again in a minute rather than concluding the video is broken.
     *
     * @throws MetaException when it is still not ready, or Meta could not process it
     */
    public function awaitVideoReady(string $videoId): void
    {
        $attempts = max(1, (int) config('platforms.meta.video_ready_attempts', 10));
        $waitMs = (int) config('platforms.meta.video_ready_wait_ms', 3000);

        for ($attempt = 1; $attempt <= $attempts; $attempt++) {
            $status = $this->graph->videoStatus($videoId);

            if ($status === 'ready') {
                return;
            }

            if ($status === 'error') {
                throw new MetaException("Meta could not process video {$videoId}, so it cannot be used in an ad.");
            }

            if ($attempt < $attempts && $waitMs > 0) {
                usleep($waitMs * 1000);
            }
        }

        throw new MetaException(
            "Video {$videoId} is still being processed by Meta. Nothing was published; try again in a minute."
        );
    }

    /** A still Meta generated from the video, which a video creative requires. */
    public function videoThumbnail(string $videoId): ?string
    {
        return $this->graph->videoThumbnail($videoId);
    }

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

    /**
     * Ask Meta to check a campaign payload without creating anything.
     *
     * Only the Graph API offers this, so it runs there even when the MCP is
     * handling creation. Cheap, and it turns "half a campaign then a rollback"
     * into a clean refusal when Meta changes its requirements.
     */
    public function validateCampaign(CampaignSpec $spec): void
    {
        $this->graph->createCampaign($spec, dryRun: true);
    }

    /**
     * Validate an ad set only when Graph created its parent campaign.
     *
     * MCP creates staged Ads Manager drafts that Graph cannot validate against.
     * The MCP has no validate-only call, so its ad sets are checked at creation.
     *
     * The status has to be the one the real create will send. It defaulted to
     * PAUSED here while createAdSet() took whichever level the publish pauses,
     * so once launches began leaving ad sets active the dry run was validating
     * a payload the create would not send - which is the one thing a dry run
     * is for.
     */
    public function validateAdSet(AdSetSpec $spec, string $status = 'PAUSED'): void
    {
        if ($this->usingMcp()) {
            return;
        }

        $this->graph->createAdSet($spec, dryRun: true, status: $status);
    }

    public function createCampaign(CampaignSpec $spec): string
    {
        if ($spec->objective === 'OUTCOME_SALES') {
            $this->salesOnGraph = true;
        }

        return ObjectId::require(
            $this->usingMcp()
                ? $this->mcp->createCampaign($spec)
                : $this->graph->createCampaign($spec),
            'campaign',
        );
    }

    /**
     * @param  string  $status  only reaches Graph. The MCP stages a draft and has
     *                          no status to set at creation; what it publishes as
     *                          is decided by settleAsPaused() below.
     */
    /**
     * Copy one ad set on Meta, with its ads, into the campaign it already belongs to.
     *
     * @return array<string, mixed>
     */
    public function copyAdSet(string $adSetId, string $campaignId, ?string $adAccountId = null, string $status = 'ACTIVE', bool $deep = true): array
    {
        return $this->graph->copyAdSet($adSetId, $campaignId, $adAccountId, $status, $deep);
    }

    /**
     * Copy one campaign on Meta without its ad sets, paused unless told otherwise.
     *
     * @return array<string, mixed>
     */
    public function copyCampaign(string $campaignId, ?string $adAccountId = null, string $status = 'PAUSED'): array
    {
        return $this->graph->copyCampaign($campaignId, $adAccountId, $status);
    }

    /**
     * Copy one ad into an ad set and leave the copy paused.
     *
     * @return array<string, mixed>
     */
    public function copyAd(string $adId, string $adSetId, ?string $adAccountId = null, string $status = 'ACTIVE'): array
    {
        return $this->graph->copyAd($adId, $adSetId, $adAccountId, $status);
    }

    /**
     * Duplicate an ad set with a pixel the ad account can use.
     *
     * Meta's copies endpoint keeps the source pixel and refuses when that pixel
     * is not assigned to the account. This reads the live targeting and creates
     * the paused copy with the pixel the user selected, then brings the ads across.
     *
     * @return array<string, mixed>
     */
    public function duplicateAdSetWithPixel(
        string $sourceAdSetId,
        string $campaignId,
        string $adAccountId,
        string $pixelId,
        ?string $name = null,
    ): array {
        $source = $this->graph->readAdSet($sourceAdSetId, $adAccountId);
        $created = $this->graph->createAdSetCopy($adAccountId, $campaignId, $source, $pixelId, $name);
        $adSetId = (string) ($created['id'] ?? '');

        if ($adSetId === '') {
            throw new MetaException('Meta did not return the copied ad set id.');
        }

        $adObjects = [];

        foreach ($this->graph->ads($sourceAdSetId, adAccountId: $adAccountId, fresh: true) as $ad) {
            $sourceAdId = (string) ($ad['id'] ?? '');

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

            try {
                $copy = $this->graph->copyAd($sourceAdId, $adSetId, $adAccountId);
                $copiedId = (string) ($copy['copied_ad_id'] ?? $copy['id'] ?? '');
            } catch (MetaException) {
                $creativeId = (string) ($ad['creative']['id'] ?? '');
                $copiedId = $creativeId === ''
                    ? ''
                    : (string) ($this->graph->createAd($adAccountId, $adSetId, $creativeId, trim((string) ($ad['name'] ?? 'Ad')).' - copy')['id'] ?? '');
            }

            if ($copiedId !== '') {
                $adObjects[] = [
                    'ad_object_type' => 'ad',
                    'source_id' => $sourceAdId,
                    'copied_id' => $copiedId,
                ];
            }
        }

        return [
            'copied_adset_id' => $adSetId,
            'status_option' => 'PAUSED',
            'ad_object_ids' => [
                ['ad_object_type' => 'ad_set', 'source_id' => $sourceAdSetId, 'copied_id' => $adSetId],
                ...$adObjects,
            ],
        ];
    }

    /** @return list<array<string, mixed>> */
    public function adsIn(string $adSetId, ?string $adAccountId = null): array
    {
        return $this->graph->ads($adSetId, adAccountId: $adAccountId, fresh: true);
    }

    public function createAdSet(AdSetSpec $spec, string $status = 'PAUSED'): string
    {
        return ObjectId::require(
            $this->usingMcp()
                ? $this->mcp->createAdSet($spec)
                : $this->graph->createAdSet($spec, status: $status),
            'ad set',
        );
    }

    /** @return array<string, mixed> */
    public function readAdSetForEventCopy(string $adSetId, string $account): array
    {
        return $this->graph->readAdSetForEventCopy($adSetId, $account);
    }

    /** @param array<string, mixed> $source */
    public function createAdSetWithEvent(string $account, string $campaignId, array $source, string $event): string
    {
        return ObjectId::require($this->graph->createAdSetCopy(
            $account, $campaignId, $source,
            (string) data_get($source, 'promoted_object.pixel_id'),
            trim((string) ($source['name'] ?? 'Ad set')).' - '.$event.' copy',
            $event,
        ), 'ad set');
    }

    /**
     * The creative is made by whichever transport will make the ad.
     *
     * Video used to go over Graph even with the MCP on, because the MCP's video
     * arguments had never been exercised against a real account and a creative
     * is the one object where the wrong shape produces an ad that exists and
     * looks wrong rather than an error. That caution turned out to cost more
     * than it saved: a Graph creative carries its own object_story_spec, and an
     * MCP draft ad that references one is refused at publish with
     * ObjectStorySpecRedundant, so the campaign could never go live at all.
     *
     * Measured on 1 Oct against act_1238155271384134 rather than reasoned about.
     * Three ads built the old way - Graph creative, MCP ad - each carried that
     * error and blocked the whole publish. The same video through
     * ads_create_creative returned a creative id and one harmless warning, and a
     * draft ad referencing it came back with active_errors empty.
     *
     * So the rule is now that the creative and the ad share a transport. Uploads
     * and deletes still go to Graph, which is a different argument: those tools
     * are gated or absent on the MCP, rather than untested.
     */
    public function createCreative(CreativeSpec $spec): string
    {
        return ObjectId::require(
            $this->usingMcp()
                ? $this->mcp->createCreative($spec)
                : $this->graph->createCreative($spec),
            'ad creative',
        );
    }

    /** @param  string  $status  only reaches Graph, for the reason given on createAdSet(). */
    public function createAd(string $adAccountId, string $adSetId, string $creativeId, string $name, string $status = 'PAUSED'): string
    {
        return ObjectId::require(
            $this->usingMcp()
                ? $this->mcp->createAd($adAccountId, $adSetId, $creativeId, $name)
                : $this->graph->createAd($adAccountId, $adSetId, $creativeId, $name, status: $status),
            'ad',
        );
    }

    /**
     * Change a live object.
     *
     * Always Graph. The Ads MCP update tool stages edits to a published object
     * - budget, bid, name, targeting, creative -
     * as an unpublished Ads Manager draft (is_draft: true) and reports success,
     * so nothing changes until somebody presses Review and publish.
     *
     * @param  array<string,mixed>  $fields  platform field names, not create arguments
     */
    public function updateEntity(string $adAccountId, string $entityId, string $entityType, array $fields): void
    {
        $this->updateLiveEntity($adAccountId, $entityId, $fields);
    }

    /**
     * Change a published object so the change is live when this returns.
     *
     * Always Graph, for the reason given on {@see updateEntity()}.
     *
     * @param  array<string,mixed>  $fields  platform field names, money in minor units
     */
    public function updateLiveEntity(string $adAccountId, string $entityId, array $fields): void
    {
        $this->graph->updateEntity($entityId, $fields, $adAccountId);
    }

    /** Pause an MCP-created object after its initial publish has become readable. */
    public function pauseCreatedObject(string $adAccountId, string $entityId, string $entityType): void
    {
        if ($this->usingMcp()) {
            $this->mcp->updateEntity($adAccountId, $entityId, $entityType, ['status' => 'PAUSED']);

            return;
        }

        $this->updateLiveEntity($adAccountId, $entityId, ['status' => 'PAUSED']);
    }

    /**
     * Schedule IDs always come from the fresh ad-set read, never an arbitrary
     * user-supplied object. Partial failure is followed by the editor's readback.
     *
     * @param  list<array<string, mixed>>  $before
     * @param  list<array<string, mixed>>  $after
     */
    public function replaceBudgetSchedules(string $adAccountId, string $adSetId, array $before, array $after): void
    {
        $known = [];
        foreach ($before as $schedule) {
            $id = $schedule['id'] ?? null;
            if (! is_string($id) || ! ctype_digit($id)) {
                throw new \RuntimeException('Meta returned a budget schedule without a usable ID.');
            }
            $known[$id] = $schedule;
        }
        foreach ($after as $schedule) {
            if (isset($schedule['id']) && ! isset($known[$schedule['id']])) {
                throw new \RuntimeException('This budget schedule does not belong to this ad set.');
            }
        }
        $keep = array_column($after, 'id');
        foreach ($known as $id => $schedule) {
            if (! in_array((string) $id, $keep, true) && ! $this->graph->delete((string) $id)) {
                throw new \RuntimeException('Meta did not confirm removal of a budget schedule.');
            }
        }
        foreach ($after as $schedule) {
            $id = $schedule['id'] ?? null;
            unset($schedule['id']);
            if ($id === null) {
                $this->graph->createBudgetSchedule($adSetId, $adAccountId, $schedule);
            } else {
                $previous = $known[$id];
                unset($previous['id']);
                if ($schedule != $previous) {
                    if (! $this->graph->delete($id)) {
                        throw new \RuntimeException('Meta did not confirm removal of the budget schedule being replaced.');
                    }
                    $this->graph->createBudgetSchedule($adSetId, $adAccountId, $schedule);
                }
            }
        }
    }

    /**
     * Pause or unpause one live campaign, ad set, or ad.
     *
     * The same Graph call for every level: POST /{object_id} with status PAUSED,
     * ACTIVE, or ARCHIVED. ARCHIVED cannot be turned back on. The MCP update
     * tool refuses ACTIVE, and ads_activate_entity only publishes a draft, so a
     * live object is changed here.
     *
     * @return array{status: string, effective_status: string}
     */
    public function setObjectStatus(string $adAccountId, string $objectId, string $status): array
    {
        $status = match (strtoupper($status)) {
            'ACTIVE' => 'ACTIVE',
            'ARCHIVED' => 'ARCHIVED',
            default => 'PAUSED',
        };
        $this->graph->updateEntity($objectId, ['status' => $status], $adAccountId);
        $read = $this->objectStatus($objectId, $adAccountId);

        return [
            'status' => strtoupper((string) ($read['status'] ?? $status)),
            'effective_status' => strtoupper((string) ($read['effective_status'] ?? '')),
        ];
    }

    /**
     * Meta's own thumbnail, handed back to Meta as an uploaded image.
     *
     * Absurd on the face of it, and still the only route. The MCP will not take
     * a video creative without image_hash or image_url, refuses the signed
     * scontent URL that videoThumbnail() returns, and /adimages answers "(#3)
     * Application does not have the capability" to a url= upload on this app.
     * That leaves fetching the bytes and posting them, which is what the image
     * path already does for an ordinary creative.
     *
     * Through PublicHttp because the address came from an API response rather
     * than from us, and everything else that fetches one goes through the same
     * guard.
     */
    public function uploadImageFromUrl(string $adAccountId, string $url, string $filename): string
    {
        $response = PublicHttp::send(Http::connectTimeout(5)->timeout(30), $url);

        if ($response->failed()) {
            throw new MetaException("The video thumbnail could not be fetched (HTTP {$response->status()}).");
        }

        $path = tempnam(sys_get_temp_dir(), 'arb-thumb-');

        try {
            file_put_contents($path, $response->body());

            return $this->graph->uploadImage($adAccountId, $path, $filename);
        } finally {
            @unlink($path);
        }
    }

    /**
     * Settle whatever creation left behind, so the campaign exists and is paused.
     *
     * Only the MCP needs this. Graph's creates send status PAUSED and produce
     * live objects, so there is nothing staged and nothing to publish; the MCP
     * produces an unpublished draft staged ACTIVE, which is neither.
     *
     * @param  list<array{id: string, type: string}>  $objects  campaign first, then ad set, then ads
     * @param  bool  $pauseChildren  false leaves the ad set and ads active under
     *                               the paused campaign. A rollback always passes
     *                               true: publishing a draft with everything
     *                               paused is the only route measured to make it
     *                               deletable through Graph.
     * @param  bool  $whenCreated  true on the create path: pause only after Graph
     *                             can see the campaign, the ad set, and the ads.
     *                             Pausing a draft that is still publishing is what
     *                             left StockPrices with a campaign and no children.
     */
    public function settleAsPaused(string $adAccountId, array $objects, bool $pauseChildren = true, bool $whenCreated = false): void
    {
        if ($this->mcp === null) {
            return;
        }

        if (! $whenCreated) {
            $this->mcp->publishDraftPaused($adAccountId, $objects, $pauseChildren);

            return;
        }

        if ($this->mcp->publishDraft($adAccountId, $objects) === []) {
            return;
        }

        app(MetaDraftPause::class)->pauseOnceCreated($adAccountId, $objects, $pauseChildren);
    }

    /**
     * Publish staged MCP drafts without pausing them.
     *
     * Graph cannot attach an ad to a draft ad set. The ad is created only after
     * this returns and {@see awaitLiveObject()} can read the ad set back.
     *
     * @param  list<array{id: string, type: string}>  $objects
     * @return array<string, mixed>
     */
    public function publishDraft(string $adAccountId, array $objects): array
    {
        if ($this->mcp === null) {
            return [];
        }

        return $this->mcp->publishDraft($adAccountId, $objects);
    }

    /**
     * Seconds between Graph reads while Meta is still publishing a draft.
     *
     * The first read is immediate. These run only while the object is missing.
     *
     * @var list<int>
     */
    public const LIVE_WAIT_SECONDS = [1, 2, 3, 5, 8, 13];

    /**
     * Read one object back once Graph can see it.
     *
     * The id in the response is the one to keep. A draft id sent to publish is
     * not always the id of the live object, and an ad created with the draft id
     * is refused with "Choose an ad set" (100/1487006).
     *
     * @return array{id: string, status: string, effective_status: string}
     *
     * @throws MetaException when the object never becomes readable
     */
    public function awaitLiveObject(string $objectId, string $type, ?string $adAccountId = null): array
    {
        foreach ([0, ...self::LIVE_WAIT_SECONDS] as $seconds) {
            if ($seconds > 0) {
                Sleep::for($seconds)->seconds();
            }

            $status = $this->objectStatus($objectId, $adAccountId);

            if ($status !== null && filled($status['id'])) {
                return $status;
            }
        }

        throw new MetaException("{$type} {$objectId} did not finish publishing, so no ad was created.");
    }

    /**
     * Status of one campaign, ad set, or ad, or null while it is still a draft.
     *
     * @return array{id: string, status: string, effective_status: string}|null
     */
    public function objectStatus(string $objectId, ?string $adAccountId = null): ?array
    {
        return $this->graph->objectStatus($objectId, $adAccountId);
    }

    /**
     * Remove an object.
     *
     * Creatives made by the MCP are deleted there; everything else goes to
     * Graph, which can delete an MCP object once it has been published.
     */
    public function delete(string $objectId, ?string $adAccountId = null, ?string $entityType = null): bool
    {
        if ($this->mcp !== null && $adAccountId !== null && $entityType === 'creative') {
            try {
                $this->mcp->deleteCreative($adAccountId, $objectId);

                return true;
            } catch (Throwable $e) {
                Log::warning('MCP creative delete failed; trying Graph', ['object' => $objectId, 'error' => $e->getMessage()]);
            }
        }

        return $this->graph->delete($objectId);
    }

    public function usingMcp(): bool
    {
        return $this->mcp !== null && ! $this->salesOnGraph;
    }
}
