<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Platforms\MetaRules;
use App\Models\Campaign;
use App\Models\User;
use App\Services\Meta\MetaException;
use App\Services\Platforms\Support\CallContext;
use App\Services\Platforms\Support\CallLogger;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;

/**
 * Two things media buying reported from production on 8 October.
 *
 * "asking me twice on bidding" - Mohsin. The bidding question is asked, answered
 * in the buyer's own words, and asked again. set_bidding took the enum and
 * nothing else, so a buyer who read "Cost per result goal" off the screen and
 * typed it back was sent to the same three options. 7 Oct 08:50 has it exactly:
 * "Cost per Result Gole", one letter out, then "Use a cost per result goal"
 * twenty seconds later, and the target cost entered twice because changing the
 * strategy reset it.
 *
 * "optimise for rate limiting" - Kaushal. 108 Meta throttles on production
 * against zero refusals from our own hourly budget, arriving in bursts: 33 across
 * 11 accounts inside one minute on 7 Oct, 21 across 7 on 8 Oct. Every throttled
 * account was hit precisely nine times, which is ATTEMPTS of 3 over three calls.
 * Meta's ad limits reset hourly and the backoff is half a second to sixteen, so
 * each retry spends the quota again and lands on the same refusal. One refusal
 * became three.
 */
class TwoThingsFromMediaBuyingFeedbackTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();

        // Pinned rather than inherited from whatever .env is on the box. A test
        // that drives CallLogger without these is refused by the allow list or
        // the kill switch before the closure runs, and then asserts about a
        // retry loop it never reached.
        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.mcp.enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['act_111'],
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.max_calls_per_hour' => 1000,
        ]);

        $this->actingAs(User::factory()->create());
    }

    // ------------------------------------------- asking twice on bidding

    private function campaign(): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Meta campaign',
            'platform' => 'meta',
            'status' => 'draft',
            'currency' => 'USD',
        ]);

        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);

        return $campaign;
    }

    /** @return array<string,mixed> */
    private function setBidding(array $arguments): array
    {
        $result = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t) => $t->name() === 'campaign__set_bidding')
            ->handle(new Request($arguments));

        return json_decode((string) $result, true);
    }

    /** @return array<string, list<string>> */
    public static function spokenStrategies(): array
    {
        return [
            'the label as shown' => ['Cost per result goal', 'COST_CAP'],
            'the label lowercased' => ['cost per result goal', 'COST_CAP'],
            'the sends text' => ['Use a cost per result goal', 'COST_CAP'],
            'the production typo' => ['Cost per Result Gole', 'COST_CAP'],
            'bid cap by name' => ['Bid cap', 'LOWEST_COST_WITH_BID_CAP'],
            'highest volume by name' => ['Highest volume', 'LOWEST_COST_WITHOUT_CAP'],
            'the enum itself' => ['COST_CAP', 'COST_CAP'],
            'the enum lowercased' => ['cost_cap', 'COST_CAP'],
        ];
    }

    #[DataProvider('spokenStrategies')]
    public function test_a_strategy_named_the_way_it_is_shown_is_understood(string $given, string $expected): void
    {
        $campaign = $this->campaign();

        $result = $this->setBidding(['strategy' => $given]);

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? '');
        $this->assertSame($expected, $campaign->fresh()->bid_strategy, "\"{$given}\" was not understood");
    }

    /** Something that is not a strategy is still refused rather than guessed. */
    public function test_nonsense_is_still_refused(): void
    {
        $campaign = $this->campaign();

        $result = $this->setBidding(['strategy' => 'whatever is cheapest for conversions on tuesdays']);

        $this->assertFalse($result['ok'] ?? true, 'a phrase matching nothing should not pick a strategy');
        $this->assertNull($campaign->fresh()->bid_strategy);
    }

    /**
     * The labels are far enough apart that a near-miss cannot be ambiguous.
     *
     * The fallback resolves a typo within two characters. If two labels were ever
     * within four of each other, one typo could sit the same distance from both
     * and the resolver would have to choose how somebody's money is bid. It
     * refuses in that case, and this test is what keeps the premise true as
     * labels change.
     */
    public function test_no_two_bid_strategy_labels_are_close_enough_to_confuse(): void
    {
        $labels = collect(app(MetaRules::class)->bidStrategyOptions())
            ->map(fn (array $option): string => (string) preg_replace('/[^a-z0-9]/', '', strtolower((string) $option['label'])))
            ->values();

        foreach ($labels as $i => $a) {
            foreach ($labels as $j => $b) {
                if ($i >= $j) {
                    continue;
                }

                $this->assertGreaterThan(4, levenshtein($a, $b), "\"{$a}\" and \"{$b}\" are too close to tell apart");
            }
        }
    }

    // ------------------------------------------- the per-account fan-out

    /**
     * Drawing the account list costs one call, not one per account.
     *
     * With 46 accounts on the production allow list this screen made 46 calls,
     * every one of them into the per-account bucket - the bucket that actually
     * gets throttled. Across every Meta call recorded: act_* 1017 calls and 108
     * throttled, me/* 111 calls and 0 throttled. The original design chose the
     * per-account edge on the belief that me/adaccounts would be throttled first,
     * which production contradicts.
     */
    public function test_the_account_list_is_fetched_in_one_call(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => [
            'act_111', 'act_222', 'act_333', 'act_444', 'act_555',
        ]]);

        Http::fake(['*' => Http::response(['data' => [
            ['id' => 'act_111', 'name' => 'One', 'currency' => 'USD', 'account_status' => 1],
            ['id' => 'act_222', 'name' => 'Two', 'currency' => 'USD', 'account_status' => 1],
            ['id' => 'act_333', 'name' => 'Three', 'currency' => 'USD', 'account_status' => 1],
            ['id' => 'act_444', 'name' => 'Four', 'currency' => 'USD', 'account_status' => 1],
            ['id' => 'act_555', 'name' => 'Five', 'currency' => 'USD', 'account_status' => 1],
        ]])]);

        $this->listAccounts();

        $perAccount = collect(Http::recorded())->filter(
            fn (array $pair): bool => (bool) preg_match('#/act_[0-9]+(\?|$)#', (string) $pair[0]->url()),
        );

        $this->assertCount(0, $perAccount, 'an account was still looked up individually');
        $this->assertCount(1, Http::recorded(), 'five accounts should cost one call');
    }

    /** An allowed account the token cannot see still gets its own lookup. */
    public function test_an_account_outside_the_tokens_list_is_still_looked_up(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => ['act_111', 'act_999']]);

        Http::fake([
            '*me/adaccounts*' => Http::response(['data' => [
                ['id' => 'act_111', 'name' => 'One', 'currency' => 'USD', 'account_status' => 1],
            ]]),
            '*' => Http::response(['id' => 'act_999', 'name' => 'Nine', 'currency' => 'USD', 'account_status' => 1]),
        ]);

        $result = $this->listAccounts();

        $ids = collect($result['ad_accounts'] ?? [])->pluck('id');

        $this->assertTrue($ids->contains('act_111'), 'the bulk account is missing');
        $this->assertTrue($ids->contains('act_999'), 'the account outside the list was dropped');
    }

    /**
     * An account beyond the first page is still found.
     *
     * One page of 50 was all me/adaccounts read. That truncated the wildcard
     * chooser outright, and now that the allow list is served from this call it
     * would also send every account it missed back to an individual lookup -
     * quietly reintroducing the fan-out this replaced.
     */
    public function test_accounts_beyond_the_first_page_are_fetched(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => ['act_111', 'act_222']]);

        $page = 0;

        Http::fake(function () use (&$page) {
            $page++;

            return $page === 1
                ? Http::response([
                    'data' => [['id' => 'act_111', 'name' => 'One', 'currency' => 'USD', 'account_status' => 1]],
                    'paging' => ['cursors' => ['after' => 'CURSOR']],
                ])
                : Http::response([
                    'data' => [['id' => 'act_222', 'name' => 'Two', 'currency' => 'USD', 'account_status' => 1]],
                ]);
        });

        $ids = collect($this->listAccounts()['ad_accounts'] ?? [])->pluck('id');

        $this->assertTrue($ids->contains('act_222'), 'the second page was never read');
        $this->assertSame(2, $page, 'paging stopped after the first page');
    }

    /** @return array<string,mixed> */
    private function listAccounts(): array
    {
        $this->campaign();

        $result = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t) => $t->name() === 'campaign__list_ad_accounts')
            ->handle(new Request([]));

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

    // ------------------------------------------------------ rate limiting

    /** @return array<string, list<string>> */
    public static function hourlyLimits(): array
    {
        return [
            'ad account limit' => ['There have been too many calls to this ad-account. Wait a bit and try again. [OAuthException 17/2446079]'],
            'application limit' => ['Application request limit reached [OAuthException 4/]'],
            'ads management limit' => ['User request limit reached [OAuthException 80004]'],
            'custom rate limit' => ['Too many calls [OAuthException 613]'],
        ];
    }

    /**
     * An hourly limit is reported once, not three times.
     *
     * @param  string  $message  as Meta words it
     */
    #[DataProvider('hourlyLimits')]
    public function test_an_hourly_limit_is_not_retried(string $message): void
    {
        $attempts = 0;

        try {
            app(CallLogger::class)->record(
                new CallContext('meta', 'GET', 'act_111', 'act_111', [], mutating: false),
                function () use (&$attempts, $message): array {
                    $attempts++;

                    throw new MetaException($message);
                },
            );
        } catch (MetaException) {
            // expected
        }

        $this->assertSame(1, $attempts, 'an hourly limit was retried, spending the quota again for the same refusal');
    }

    /** A transport blip is still worth another go. */
    public function test_a_transient_failure_is_still_retried(): void
    {
        config(['platforms.guardrails.retry_backoff_ms' => 0]);

        $attempts = 0;

        try {
            app(CallLogger::class)->record(
                new CallContext('meta', 'GET', 'act_111', 'act_111', [], mutating: false),
                function () use (&$attempts): array {
                    $attempts++;

                    throw new MetaException('Service temporarily unavailable [503]');
                },
            );
        } catch (MetaException) {
            // expected
        }

        $this->assertGreaterThan(1, $attempts, 'a 503 should still be retried');
    }
}
