<?php

namespace App\Services\Platforms\Support;

use App\Models\ApiCall;
use App\Services\LinkedIn\LinkedInException;
use App\Services\Meta\MetaException;
use App\Services\Meta\ObjectId;
use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Sleep;

/**
 * Wraps remote calls to ad platforms: guardrails before, audit row after,
 * whatever the outcome. api_calls records remote attempts across transports,
 * not user accesses: request-local and persistent cache hits create no rows
 * and do not spend the remote-call budget.
 *
 * Lived in App\Services\Meta while Meta was the only platform, which made it
 * look like Meta's own bookkeeping rather than the one place every call is
 * counted, allow-listed and recorded. Google Ads goes through it too, and a
 * platform that does not is a platform outside the call budget and outside the
 * audit trail.
 */
class CallLogger
{
    /** Attempts at one call, when the platform only refused to take it. */
    private const ATTEMPTS = 3;

    /**
     * Seconds to wait before each retry of a LinkedIn conversion association
     * that LinkedIn refused because the campaign was only just created.
     *
     * Measured against ad account 556447014 on 20 Oct: the PUT answers 404
     * "does not have permission to UPDATE" for roughly the first 5 to 9
     * seconds of a new campaign's life, then 204 with the same token, with a
     * new or an existing campaign group alike. The generic backoff gave up
     * after about 2.5 seconds, so production rolled every conversion campaign
     * back. Four retries spaced 5, 5, 10 and 15 seconds cover 35 seconds.
     *
     * @var list<int>
     */
    private const LINKEDIN_CONVERSION_ASSOCIATION_RETRY_SECONDS = [5, 5, 10, 15];

    /** How much of a response is kept. Bytes, because that is what a column holds. */
    private const MAX_RESPONSE_BYTES = 4000;

    /**
     * How a platform says "not now" rather than "no".
     *
     * These are refusals, not failures: the request was never processed, which
     * is what makes repeating one safe even for a write. Matched on the message
     * because every transport flattens the error into it, codes included.
     *
     * Meta: 80004 is the ads-management hourly limit, 613 the calls-per-hour
     * limit, 17 the per-user limit and 4 the per-app one. All four blocked real
     * work during testing.
     *
     * Google: quota refusals arrive as RESOURCE_EXHAUSTED, and the Ads API
     * reports its own limits as RATE_EXCEEDED with a retry delay.
     */
    private const THROTTLED = [
        'too many calls',
        'rate limit',
        'request limit reached',
        'reduce the amount of data',
        '80004',
        '613',
        ' 17/',
        ' 4/',
        '429',
        '503',
        'resource_exhausted',
        'rate_exceeded',
        'quota',
    ];

    /**
     * The throttles measured by the hour, which retrying makes worse.
     *
     * Meta's ad limits reset hourly. The backoff here is 0.5 to 16 seconds, so a
     * retry cannot clear one - it just spends the quota again and lands on the
     * same refusal. With ATTEMPTS at 3 that turns one refusal into three, and the
     * production record shows exactly that: every throttled account hit precisely
     * nine times, in bursts of 33 across 11 accounts in a single minute on 7 Oct
     * and 21 across 7 on 8 Oct, 108 in total. None of them were our own budget
     * refusing; all were Meta's.
     *
     * So these fail once and report, and the hour they need is spent waiting
     * rather than spent on calls that cannot succeed. That is two thirds of the
     * throttled volume removed without changing what anybody asks for.
     *
     * Kept separate from THROTTLED rather than removed from it. Removing them
     * would reach the same decision, because what is left refuses anything that
     * is not a non-mutating timeout - but THROTTLED is the written record of how
     * every platform says "not now", and MetaApiError's permanent wording is
     * checked against that list by hand. Shrinking it would quietly narrow what
     * that check is read against.
     */
    private const HOURLY_LIMIT = [
        'too many calls',
        'request limit reached',
        '80004',
        '613',
        ' 17/',
        ' 4/',
        '2446079',
    ];

    private ?int $campaignId = null;

    private ?string $actor = null;

    public function __construct(
        private readonly Guardrails $guardrails,
    ) {}

    public function attributeTo(?int $campaignId, ?string $actor): static
    {
        $this->campaignId = $campaignId;
        $this->actor = $actor;

        return $this;
    }

    /**
     * Reads already made in this request, keyed by what was asked.
     *
     * Request scoped by construction. Selected discovery endpoints can also
     * opt into a persistent cache through their CallContext TTL and scope.
     *
     * @var array<string, array<string,mixed>>
     */
    private array $reads = [];

    private function memoKey(CallContext $context): string
    {
        return implode('|', [
            $context->platform,
            $context->transport,
            $context->method,
            $context->endpoint,
            $context->adAccountId ?? '',
            $context->credentialScope ?? '',
            md5(json_encode($context->request) ?: ''),
            ...($context->discoveryGroup === null ? [] : [Cache::get(
                $this->discoveryGenerationKey($context->credentialScope ?? '', $context->discoveryGroup), '',
            )]),
        ]);
    }

    public function invalidateDiscovery(string $credentialScope, string $group): void
    {
        // A new namespace also invalidates pagination and request-local reads.
        // In-flight reads can only populate the old namespace.
        Cache::forever($this->discoveryGenerationKey($credentialScope, $group), bin2hex(random_bytes(16)));
    }

    private function discoveryGenerationKey(string $credentialScope, string $group): string
    {
        return 'platform-discovery-generation:'.hash('sha256', $credentialScope.'|'.$group);
    }

    /**
     * @param  \Closure(): array<string,mixed>  $call
     * @return array<string,mixed>
     *
     * @throws MetaException
     */
    public function record(CallContext $context, \Closure $call): array
    {
        return $this->recordCall($context, $call);
    }

    /** @param \Closure(): array<string, mixed> $call */
    private function recordCall(CallContext $context, \Closure $call, bool $locked = false): array
    {
        // A cached read still needs the current account permission check.
        // Access can change while a worker or a request holds this logger.
        if ($context->accountChecked && $context->adAccountId) {
            $this->guardrails->assertAccountAllowed($context->adAccountId, $context->platform);
        }

        // The same read, asked for again inside one request.
        //
        // Measured on dev: 86 of 306 non-mutating calls were exact repeats
        // within ten seconds, costing 34.8 seconds of somebody's turn. One ad
        // account was read seven times while building a single campaign,
        // because every tool that needs its name or currency fetches it, and
        // none of them knew another already had.
        //
        // Most reads are reused only within the request. Discovery reads may
        // additionally specify a persistent TTL; live validation does not.
        //
        // No audit row for a repeat, because no call was made. The trail
        // records what reached the platform.
        $memo = $context->mutating || ! $context->memoize ? null : $this->memoKey($context);

        if ($memo !== null && array_key_exists($memo, $this->reads)) {
            return $this->reads[$memo];
        }

        $cacheKey = $memo !== null && $context->credentialScope !== null && $context->cacheSeconds > 0
            ? 'platform-discovery:'.hash('sha256', $memo)
            : null;

        if ($cacheKey !== null && is_array($cached = Cache::get($cacheKey))
            && $this->isCacheableDiscoveryResult($context, $cached)) {
            return $this->reads[$memo] = $cached;
        }

        if ($cacheKey !== null && ! $locked && $context->platform === 'meta' && $context->transport === 'graph'
            && (bool) config('platforms.meta.discovery_coalescing', true)) {
            try {
                return Cache::lock($cacheKey.':lock', 240)->block(
                    5,
                    fn (): array => $this->recordCall($context, $call, locked: true),
                );
            } catch (LockTimeoutException $exception) {
                Log::notice('Discovery is already being fetched', [
                    'platform' => $context->platform, 'endpoint' => $context->endpoint,
                    'ad_account_id' => $context->adAccountId,
                ]);

                throw new MetaException('Discovery is already being fetched. No duplicate request was sent. Try again shortly.', previous: $exception);
            }
        }

        if ($context->guarded && $context->mutating) {
            $this->guardrails->assertWritesAllowed();
        }

        $attempt = 0;

        while (true) {
            $attempt++;

            // Re-checked every attempt, not once. Each attempt is a real call
            // against Meta's quota and writes its own api_calls row, so a
            // throttled burst could take the budget two calls past its limit
            // while the check that exists to prevent exactly that had already
            // run and passed.
            if ($context->guarded) {
                $this->assertOutsideMetaCooldown($context);
                $this->guardrails->assertWithinCallBudget($context->adAccountId);
            }

            try {
                $result = $this->attempt($context, $call);

                if ($memo !== null) {
                    $this->reads[$memo] = $result;
                }

                if ($cacheKey !== null && $this->isCacheableDiscoveryResult($context, $result)) {
                    Cache::put($cacheKey, $result, $context->cacheSeconds);
                }

                return $result;
            } catch (\Throwable $e) {
                if ($this->startMetaCooldown($context, $e)) {
                    throw $e;
                }

                // Checked before the generic rules: its own longer schedule,
                // and the campaign id in the message could match a throttle code.
                if ($this->isLinkedInCampaignConversionPropagationDelay($e, $context)) {
                    $wait = self::LINKEDIN_CONVERSION_ASSOCIATION_RETRY_SECONDS[$attempt - 1] ?? null;

                    if ($wait === null) {
                        throw $e;
                    }

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

                    continue;
                }

                if (! $this->worthRetrying($e, $context, $attempt)) {
                    throw $e;
                }

                // Meta's limits are per hour, so a few hundred milliseconds
                // will not clear one. Long enough to ride out a burst, short
                // enough that somebody watching a spinner does not give up.
                // Configurable so the test suite does not sit through it.
                $step = (int) config('platforms.guardrails.retry_backoff_ms', 500);

                if ($step > 0) {
                    usleep(min($attempt * $attempt, 16) * $step * 1000);
                }
            }
        }
    }

    /**
     * Empty interest searches may recover on the next turn, so they must not
     * persist for the full discovery TTL, including entries cached previously.
     *
     * @param  array<string, mixed>  $result
     */
    private function isCacheableDiscoveryResult(CallContext $context, array $result): bool
    {
        if ($context->platform === 'meta' && $context->transport === 'graph'
            && (str_ends_with($context->endpoint, '/targetingsearch')
                || str_ends_with($context->endpoint, '/targetingsuggestions'))) {
            return is_array($result['data'] ?? null) && $result['data'] !== [];
        }

        if ($context->platform === 'meta' && $context->transport === 'graph'
            && (str_ends_with($context->endpoint, '/targetingbrowse')
                || ($context->endpoint === 'search' && ($context->request['type'] ?? null) === 'adTargetingCategory'))) {
            return is_array($result['data'] ?? null) && $result['data'] !== [];
        }

        if ($context->discoveryGroup !== null) {
            return is_array($result['data'] ?? null);
        }

        return true;
    }

    /**
     * Whether this failure is worth trying again.
     *
     * A throttle is an explicit refusal: Meta says it did not process the
     * request, so repeating it cannot create a second campaign. A timeout says
     * nothing of the sort. The reply may have been lost after the work was
     * done, so a write that times out is never repeated, which is the same
     * reasoning as the double publish guard.
     */
    private function metaCooldownKey(CallContext $context, ?string $account = null): string
    {
        return 'meta-quota-cooldown:'.hash('sha256', $context->quotaScope.'|'.($account ?? 'token'));
    }

    private function assertOutsideMetaCooldown(CallContext $context): void
    {
        if ($context->platform !== 'meta' || $context->transport !== 'graph'
            || $context->quotaScope === null || (int) config('platforms.meta.cooldown_seconds', 300) <= 0) {
            return;
        }

        $keys = [$this->metaCooldownKey($context)];

        if ($context->adAccountId !== null) {
            $keys[] = $this->metaCooldownKey($context, $context->adAccountId);
        }

        foreach ($keys as $key) {
            $until = Cache::get($key);

            if (is_numeric($until) && (int) $until > now()->timestamp) {
                throw new MetaException('Meta quota cooldown is active. No new request was sent. Try again in '
                    .((int) $until - now()->timestamp).' seconds; Meta may require a longer wait.');
            }
        }
    }

    private function startMetaCooldown(CallContext $context, \Throwable $exception): bool
    {
        $seconds = max(0, (int) config('platforms.meta.cooldown_seconds', 300));

        if ($context->platform !== 'meta' || $context->transport !== 'graph' || ! $context->guarded
            || $context->quotaScope === null || $seconds === 0 || ! $exception instanceof MetaException
            || ! in_array($exception->getCode(), [4, 17, 32, 613, 80004], true)) {
            return false;
        }

        $accountLimit = $exception->getCode() === 80004
            || ($exception->diagnostics()['meta_error_subcode'] ?? null) === 2446079;
        $key = $this->metaCooldownKey($context, $accountLimit ? $context->adAccountId : null);
        Cache::put($key, now()->timestamp + $seconds, $seconds);

        return true;
    }

    private function worthRetrying(\Throwable $e, CallContext $context, int $attempt): bool
    {
        if ($attempt >= self::ATTEMPTS) {
            return false;
        }

        $message = strtolower($e->getMessage());

        // Before the throttle list, because the hourly ones are in it.
        foreach (self::HOURLY_LIMIT as $sign) {
            if (str_contains($message, $sign)) {
                return false;
            }
        }

        foreach (self::THROTTLED as $sign) {
            if (str_contains($message, $sign)) {
                return true;
            }
        }

        // Everything else is only safe to repeat when it changed nothing.
        return ! $context->mutating
            && (str_contains($message, 'timed out') || str_contains($message, 'timeout'));
    }

    private function isLinkedInCampaignConversionPropagationDelay(\Throwable $exception, CallContext $context): bool
    {
        if (! $exception instanceof LinkedInException
            || $context->platform !== 'linkedin'
            || ! $context->mutating
            || ! str_starts_with($context->endpoint, 'rest/campaignConversions/')) {
            return false;
        }

        return ($exception->diagnostics()['http_status'] ?? null) === 404
            && str_contains(strtolower($exception->getMessage()), 'does not have permission to update the resource');
    }

    /** One attempt, timed and recorded whatever the outcome. */
    private function attempt(CallContext $context, \Closure $call): array
    {
        $startedAt = microtime(true);
        $response = null;
        $error = null;
        $diagnostics = [];
        $durationMs = null;

        try {
            return $response = $call();
        } catch (\Throwable $e) {
            $error = $e->getMessage();

            if ($e instanceof MetaException || $e instanceof LinkedInException) {
                $diagnostics = $this->guardrails->scrubCredentials($e->diagnostics());

                if ($diagnostics !== []) {
                    if ($context->transport === 'mcp') {
                        $durationMs = (int) round((microtime(true) - $startedAt) * 1000);

                        Log::error('Ad platform MCP call failed', [
                            'campaign_id' => $this->campaignId,
                            'actor' => $this->actor,
                            'platform' => $context->platform,
                            'transport' => $context->transport,
                            'endpoint' => $context->endpoint,
                            'ad_account_id' => $context->adAccountId,
                            'error' => $error,
                            'diagnostics' => $diagnostics,
                            'duration_ms' => $durationMs,
                        ]);
                    }
                }
            }

            throw $e;
        } finally {
            $durationMs ??= (int) round((microtime(true) - $startedAt) * 1000);

            ApiCall::create([
                'campaign_id' => $this->campaignId,
                'actor' => $this->actor,
                // Never written, so every row took the column default and all
                // 390 of them said meta, Google's included. The guardrails were
                // unaffected because they are handed $context->platform
                // directly; it was the audit trail that was wrong, which is the
                // one thing an audit trail cannot be.
                'platform' => $context->platform,
                'transport' => $context->transport,
                'method' => $context->method,
                // Rest.li finders carry whole targeting criteria in the URL; the column holds 255.
                'endpoint' => mb_substr($context->endpoint, 0, 255),
                'ad_account_id' => $context->adAccountId,
                'mutating' => $context->mutating,
                'dry_run' => $context->dryRun,
                'request' => $this->guardrails->scrub($context->request),
                'response' => $this->truncate($response ?? ($diagnostics !== [] ? ['_error_diagnostics' => $diagnostics] : null)),
                // This is the upstream HTTP status, not operation success. An
                // MCP tool error can be HTTP 200, so check `ok` and `error` too.
                'status' => $error === null ? 200 : ($diagnostics['http_status'] ?? null),
                'ok' => $error === null,
                'object_id' => $error === null && $response ? ObjectId::find($response) : null,
                'error' => $error ? mb_substr($error, 0, 900) : null,
                'duration_ms' => $durationMs,
            ]);
        }
    }

    /**
     * Keep enough of the response to diagnose a shape change, not all of it.
     *
     * This cut the encoded JSON at 4000 characters and decoded the offcut. JSON
     * cut mid-structure is not JSON, so json_decode returned null and the column
     * was written null - for every response over the limit and no other. The
     * small responses were kept in full and the large ones were thrown away
     * entirely, which is the opposite of what a log is for: 25 successful calls
     * in the local log have no response recorded, and they are the account lists
     * and campaign lists, exactly the ones whose shape anyone would want to see.
     *
     * So the data is reduced rather than the text cut: long strings shortened,
     * long lists capped, both marked, each pass tighter than the last until it
     * fits. What comes out is valid, readable, and still shaped like the response.
     */
    private function truncate(?array $response): ?array
    {
        if ($response === null) {
            return null;
        }

        if ($this->fits($response)) {
            return $this->reduce($response, PHP_INT_MAX, PHP_INT_MAX);
        }

        foreach ([[20, 500], [5, 200], [2, 80], [1, 40]] as [$items, $chars]) {
            $reduced = $this->reduce($response, $items, $chars);

            if ($this->fits($reduced)) {
                return $reduced;
            }
        }

        // A response that will not fit even one shortened item of each list still
        // has a shape, and the shape is the thing being diagnosed.
        return ['_truncated' => 'only the keys fit', 'keys' => array_keys($response)];
    }

    private function fits(array $value): bool
    {
        return strlen((string) json_encode($value)) <= self::MAX_RESPONSE_BYTES;
    }

    /**
     * The same data, smaller, and still the same shape.
     *
     * access_token is dropped at every depth on the way through. Guardrails::scrub
     * does that for the request but only at the top level, and a response can
     * carry one nested - me/accounts returns a page token per page when the field
     * is asked for. A log is a bad place to learn that.
     */
    private function reduce(mixed $value, int $items, int $chars): mixed
    {
        if (is_string($value)) {
            return mb_strlen($value) <= $chars
                ? $value
                : mb_substr($value, 0, $chars).sprintf('… [%d chars]', mb_strlen($value));
        }

        if (! is_array($value)) {
            return $value;
        }

        $isList = array_is_list($value);
        $reduced = [];

        foreach ($isList ? array_slice($value, 0, $items) : $value as $key => $item) {
            if (is_string($key) && strcasecmp($key, 'access_token') === 0) {
                continue;
            }

            $reduced[$key] = $this->reduce($item, $items, $chars);
        }

        if ($isList && count($value) > $items) {
            $reduced[] = sprintf('… [%d more]', count($value) - $items);
        }

        return $reduced;
    }
}
