<?php

namespace App\Services\Meta;

use App\Services\Platforms\Support\CallContext;
use App\Services\Platforms\Support\CallLogger;
use App\Support\CurrencyMinorUnits;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Sleep;

/**
 * Meta's Ads MCP.
 *
 * Preferred for creation because Meta owns the validation: it rejects illegal
 * objective and optimisation pairings, applies its own defaults, and returns the
 * valid optimisation goals alongside a new campaign. Breaking changes to the
 * request format become Meta's problem rather than ours.
 *
 * It does not create anything live, and it does not create anything paused
 * either. Every create tool here stages an unpublished draft in Ads Manager,
 * and stages it ACTIVE - so the objects exist, are not served, and are set to
 * start the moment somebody presses Review and publish. This docblock used to
 * claim it "creates everything paused", which is why nothing published through
 * the MCP was ever really published: the drafts sat in the account staged to
 * run, and every campaign this product reported as live on production was one of
 * them. {@see publishDraftPaused()} is the step that was missing.
 *
 * It cannot replace the Graph API entirely, for two reasons verified against
 * the live endpoint rather than assumed:
 *
 *   Uploads   Every upload tool is still gated ("gradually rolled out") on our
 *             accounts, and the local-file variant is interactive by design: it
 *             opens Meta's own picker for a human. The only server-to-server
 *             path is upload_source=URL, which would mean publishing every
 *             creative to a public URL first. Graph takes the bytes directly.
 *
 *   Deletion  There is no delete tool for campaigns, ad sets or ads. Creatives,
 *             images and custom audiences can be deleted; the objects the
 *             rollback path unwinds cannot.
 *
 * Requires the ads_mcp_management scope. Replies arrive as server-sent events.
 */
class AdsMcp
{
    /**
     * Seconds to wait before each further attempt at the pause while Meta is
     * still publishing. Meta's own guidance is "a minute or two", so the
     * budget adds up to two minutes across three retries.
     *
     * @var list<int>
     */
    public const PAUSE_RETRY_SECONDS = [20, 40, 60];

    public function __construct(
        private readonly string $token,
        private readonly string $endpoint,
        private readonly CallLogger $log,
    ) {}

    /** @param  list<string>  $specialAdCategories */
    public function createCampaign(CampaignSpec $spec): array
    {
        $arguments = array_filter([
            'ad_account_id' => $this->bare($spec->adAccountId),
            'campaign_name' => $spec->name,
            'objective' => $spec->objective,
            'buying_type' => 'AUCTION',
            // Was hardcoded empty. NONE is our own answer and Meta expects it
            // as an empty list, so it is filtered rather than sent.
            'special_ad_categories' => json_encode($spec->declaredCategories()),
            ...$spec->budgetFields(),
        ], fn (mixed $value): bool => $value !== null);
        unset($arguments['advantage_catalog_ads'], $arguments['catalog_id'], $arguments['product_catalog_id'], $arguments['promoted_object']);

        return $this->call('ads_create_campaign', $arguments,
            $spec->adAccountId,
            "Create a {$spec->objective} campaign named {$spec->name}",
        );
    }

    public function createAdSet(AdSetSpec $spec): array
    {
        return $this->call('ads_create_ad_set', array_filter([
            'ad_account_id' => $this->bare($spec->adAccountId),
            'campaign_id' => $spec->campaignId,
            'ad_set_name' => $spec->name,
            '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,
            ...$spec->budgetFields(),
            ...$spec->schedule(),
            ...$spec->advertiserFields(),
        ], fn (mixed $value): bool => $value !== null),
            $spec->adAccountId,
            $this->adSetSummary($spec),
        );
    }

    /** What the audit log records the call as, in money rather than minor units. */
    private function adSetSummary(AdSetSpec $spec): string
    {
        if ($spec->budgetLevel === 'campaign') {
            return "Ad set {$spec->name}, budget held on the campaign";
        }

        return sprintf(
            'Ad set %s at %s %s',
            $spec->name,
            number_format(CurrencyMinorUnits::toMajor($spec->budgetMinorUnits, $spec->currency), 2),
            $spec->budgetMode === 'lifetime' ? 'in total' : 'a day',
        );
    }

    public function createCreative(CreativeSpec $spec): array
    {
        return $this->call('ads_create_creative', $spec->mcpArguments(), $spec->adAccountId, "Ad creative {$spec->name}");
    }

    public function createAd(string $adAccountId, string $adSetId, string $creativeId, string $name): array
    {
        return $this->call('ads_create_ad', [
            'ad_account_id' => $this->bare($adAccountId),
            'ad_set_id' => $adSetId,
            'ad_name' => $name,
            'creative' => json_encode(['creative_id' => $creativeId]),
        ], $adAccountId, "Ad {$name}");
    }

    /**
     * Change fields on a live campaign, ad set or ad.
     *
     * Meta names update fields differently from create arguments: a campaign's
     * budget is daily_budget here and campaign_daily_budget on create. Callers
     * pass the update names.
     *
     * @param  array<string,mixed>  $fields
     */
    public function updateEntity(string $adAccountId, string $entityId, string $entityType, array $fields): array
    {
        return $this->call('ads_update_entity', [
            'ad_account_id' => $this->bare($adAccountId),
            'entity_id' => $entityId,
            'entity_type' => $entityType,
            'fields' => json_encode($fields),
        ], $adAccountId, 'Update '.$entityType.' '.$entityId);
    }

    public function activateEntity(string $adAccountId, string $entityId, string $entityType): array
    {
        return $this->call('ads_activate_entity', [
            'ad_account_id' => $this->bare($adAccountId),
            'entity_id' => $entityId,
            'entity_type' => $entityType,
            'object_ids' => [$entityId],
            'publish_as_active' => true,
        ], $adAccountId, 'Activate '.$entityType.' '.$entityId);
    }

    public function deleteCreative(string $adAccountId, string $creativeId): array
    {
        return $this->call('ads_creative_delete', [
            'ad_account_id' => $this->bare($adAccountId),
            'creative_id' => $creativeId,
        ], $adAccountId, 'Delete ad creative '.$creativeId);
    }

    /**
     * Publish the staged draft without pausing it.
     *
     * The create path pauses later, and only after the campaign, ad set, and ads
     * are readable. Pausing in this same call is what campaign 259 refused with
     * 1815558 while the children were still drafts.
     *
     * @param  list<array{id: string, type: string}>  $objects
     * @return array<string,mixed>
     */
    public function publishDraft(string $adAccountId, array $objects): array
    {
        $objects = array_values(array_filter(
            $objects,
            fn (array $object): bool => filled($object['id'] ?? null) && filled($object['type'] ?? null),
        ));
        $root = collect($objects)->firstWhere('type', 'campaign') ?? ($objects[0] ?? null);

        if ($root === null) {
            return [];
        }

        return $this->call('ads_activate_entity', [
            'ad_account_id' => $this->bare($adAccountId),
            'entity_id' => $root['id'],
            'entity_type' => $root['type'],
            'object_ids' => array_column($objects, 'id'),
            'publish_as_active' => false,
        ], $adAccountId, 'Publish the staged campaign, paused');
    }

    /**
     * Publish the staged draft and pause it immediately.
     *
     * Rollback only. A new campaign uses {@see publishDraft()} and then waits
     * until the campaign, ad set, and ads are readable before anything is paused.
     *
     * @param  list<array{id: string, type: string}>  $objects  campaign first, then
     *                                                          ad sets, then ads
     * @return array<string,mixed> the activate reply, plus `unpaused_objects`
     *                             (list of objects) when a pause never landed
     */
    public function publishDraftPaused(string $adAccountId, array $objects, bool $pauseChildren = true): array
    {
        $published = $this->publishDraft($adAccountId, $objects);

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

        $objects = array_values(array_filter(
            $objects,
            fn (array $object): bool => filled($object['id'] ?? null) && filled($object['type'] ?? null),
        ));

        $pending = [];

        foreach ($objects as $object) {
            if ($object['type'] !== 'campaign' && ! $pauseChildren) {
                continue;
            }

            if (! $this->tryPause($adAccountId, $object)) {
                $pending[] = $object;
            }
        }

        foreach (self::PAUSE_RETRY_SECONDS as $seconds) {
            if ($pending === []) {
                break;
            }

            Sleep::for($seconds)->seconds();

            // Only what was refused is retried; anything paused stays paused.
            $pending = array_values(array_filter(
                $pending,
                fn (array $object): bool => ! $this->tryPause($adAccountId, $object),
            ));
        }

        if ($pending !== []) {
            Log::critical('Meta campaign published but the pause never landed, it may be live', [
                'ad_account_id' => $adAccountId,
                'objects' => $pending,
            ]);

            $published['unpaused_objects'] = $pending;
        }

        return $published;
    }

    /**
     * One attempt to restage an object PAUSED.
     *
     * @param  array{id: string, type: string}  $object
     * @return bool true when paused, false when Meta is still publishing the
     *              draft. Any other refusal is real and is thrown.
     */
    private function tryPause(string $adAccountId, array $object): bool
    {
        try {
            $this->updateEntity($adAccountId, $object['id'], $object['type'], ['status' => 'PAUSED']);

            return true;
        } catch (MetaException $exception) {
            if (! $this->publishStillRunning($exception)) {
                throw $exception;
            }

            Log::warning('Meta is still publishing the draft, so the pause waits for that publish', [
                'ad_account_id' => $adAccountId,
                'entity_id' => $object['id'],
                'entity_type' => $object['type'],
                'error' => $exception->getMessage(),
            ]);

            return false;
        }
    }

    /**
     * Meta refuses an edit while the publish from ads_activate_entity is still running.
     *
     * Campaign 257 on act_1418821929380936: the pause got 1815558, the rollback's
     * second activate was told everything was already publishing, and the ad set
     * was left behind. SearchGPT finished the publish before the pause, so the
     * same sequence succeeded there.
     */
    private function publishStillRunning(MetaException $exception): bool
    {
        return $exception->isDraftStillPublishing();
    }

    /** @return list<array<string,mixed>> every account, with its MCP eligibility */
    public function adAccounts(): array
    {
        return $this->call('ads_get_ad_accounts', [], null)['ad_accounts'] ?? [];
    }

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

    /**
     * @param  string|null  $advertiserRequest  the user's own words; Meta asks for
     *                                          these to be passed through, not paraphrased
     */
    private function call(string $tool, array $arguments, ?string $adAccountId, ?string $advertiserRequest = null): array
    {
        // Meta requires this on every call and uses it to correlate a session.
        $arguments['client_conversation_id'] = 'arb-'.($adAccountId ?? 'general');

        if ($advertiserRequest !== null) {
            $arguments['advertiser_request'] = $advertiserRequest;
        }

        return $this->log->record(
            new CallContext('mcp', 'CALL', $tool, $adAccountId, $arguments, mutating: self::writes($tool)),
            fn (): array => $this->invoke($tool, $arguments),
        );
    }

    /** Verbs that mutate. Checked before the read tests below, deliberately. */
    private const MUTATING_VERBS = [
        'create', 'update', 'delete', 'remove', 'destroy', 'add', 'set',
        'upload', 'pause', 'resume', 'unpause', 'activate', 'deactivate',
        'enable', 'disable', 'archive', 'duplicate', 'copy', 'publish',
        'edit', 'modify', 'assign', 'connect', 'disconnect', 'boost',
    ];

    /**
     * Whether a tool changes anything, decided by what is known to be a read.
     *
     * This was "the name contains create", which classed ads_update_entity as a
     * read. That is the call that moves a live campaign's budget, and because
     * the kill switch only applies to mutating calls, setting
     * PLATFORM_PAUSE_ALL_WRITES would not have stopped it.
     *
     * Inverted deliberately: anything not recognisably a read counts as a
     * write, so a tool nobody has seen yet is treated as dangerous rather than
     * harmless.
     *
     * The mutating verbs are checked first, and that order is the whole point.
     * Asking only "does this look like a read" and inverting the answer puts
     * the read test first by construction, so a name carrying both - Meta's
     * convention is `ads_<resource>_<verb>_<thing>`, which makes
     * `ads_get_or_create_audience` perfectly plausible - matched `ads_get_`,
     * was called as a read, and skipped assertWritesAllowed() entirely. The
     * same shape as the ads_update_entity defect above, one layer along.
     *
     * The cost of this order is a read that happens to carry a mutating word,
     * `ads_catalog_get_product_feed_upload_sessions` being the real example,
     * which is refused while the kill switch is on. None of the tools this
     * class calls is one, and a read wrongly held is the side to err on.
     */
    private static function writes(string $tool): bool
    {
        foreach (self::MUTATING_VERBS as $verb) {
            if (str_starts_with($tool, $verb) || str_contains($tool, '_'.$verb)) {
                return true;
            }
        }

        $reads = str_starts_with($tool, 'ads_get_')
            || str_contains($tool, '_get_')
            || str_contains($tool, '_list_')
            || in_array($tool, ['ads_library_search', 'ads_insights_anomaly_signal'], true);

        return ! $reads;
    }

    private function invoke(string $tool, array $arguments): array
    {
        $body = [
            'jsonrpc' => '2.0',
            'id' => 1,
            'method' => 'tools/call',
            'params' => ['name' => $tool, 'arguments' => $arguments],
        ];

        $response = Http::timeout(120)
            ->withToken($this->token)
            ->withHeaders(['Accept' => 'application/json, text/event-stream'])
            ->post($this->endpoint, $body);

        if ($tool === 'ads_update_entity') {
            Log::info('Meta ads_update_entity', [
                'url' => $this->endpoint,
                'payload' => $body,
                'status' => $response->status(),
                'response' => $response->body(),
            ]);
        }

        $diagnostics = [
            'http_status' => $response->status(),
            'correlation_headers' => array_filter([
                'x-request-id' => $response->header('x-request-id'),
                'request-id' => $response->header('request-id'),
                'x-correlation-id' => $response->header('x-correlation-id'),
                'traceparent' => $response->header('traceparent'),
                'x-fb-trace-id' => $response->header('x-fb-trace-id'),
                'x-fb-rev' => $response->header('x-fb-rev'),
            ], fn (?string $value): bool => filled($value)),
        ];

        if (! $response->successful()) {
            throw new MetaException(
                sprintf('Meta Ads MCP returned HTTP %d on %s', $response->status(), $tool),
                diagnostics: $diagnostics,
            );
        }

        $envelope = $this->decodeEventStream($response->body());

        if ($error = $envelope['error'] ?? null) {
            throw new MetaException(sprintf(
                '%s [MCP %s] on %s',
                $error['message'] ?? 'unknown MCP error',
                $error['code'] ?? '?',
                $tool,
            ), diagnostics: [
                ...$diagnostics,
                'jsonrpc_error' => $error,
            ]);
        }

        $result = $envelope['result'] ?? null;

        if (! is_array($result)) {
            throw new MetaException(
                sprintf('Meta Ads MCP response did not contain a result on %s', $tool),
                diagnostics: [
                    ...$diagnostics,
                    'response_bytes' => strlen($response->body()),
                    'content_type' => $response->header('content-type'),
                ],
            );
        }

        $text = collect($result['content'] ?? [])->pluck('text')->implode('');
        $payload = json_decode($text, true) ?: ['text' => $text];

        // A tool can run successfully and still report that the operation
        // failed, so isError has to be checked separately from the JSON-RPC
        // error above.
        if (($result['isError'] ?? false) || isset($payload['error'])) {
            $reason = $payload['error']['message'] ?? $payload['error'] ?? $payload['message'] ?? mb_substr($text, 0, 300);

            throw new MetaException(sprintf(
                '%s [MCP] on %s',
                is_string($reason) ? $reason : json_encode($reason),
                $tool,
            ), diagnostics: [
                ...$diagnostics,
                'mcp_is_error' => (bool) ($result['isError'] ?? false),
                'mcp_payload' => $payload,
            ]);
        }

        return $payload;
    }

    /** The payload arrives on a `data:` line rather than as a plain body. */
    private function decodeEventStream(string $body): array
    {
        foreach (explode("\n", $body) as $line) {
            if (str_starts_with($line = trim($line), 'data: ')) {
                return json_decode(substr($line, 6), true) ?: [];
            }
        }

        return json_decode($body, true) ?: [];
    }

    /** The MCP wants a bare numeric id; the Graph API wants the act_ prefix. */
    private function bare(string $adAccountId): string
    {
        return ltrim(str_replace('act_', '', $adAccountId), '_');
    }
}
