<?php

namespace Tests\Feature;

use App\Services\Meta\AdsMcp;
use App\Services\Meta\MetaException;
use App\Services\Platforms\Support\CallLogger;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Log\Events\MessageLogged;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use ReflectionMethod;
use Tests\TestCase;

/**
 * PLATFORM_PAUSE_ALL_WRITES only stops calls classified as mutating.
 *
 * That makes AdsMcp::writes() part of the kill switch rather than a label on a
 * log line: a tool it calls a read is sent while every write is being refused.
 *
 * It has been wrong in that direction once already. It used to test whether
 * the name contained "create", which made ads_update_entity - the call that
 * moves a live campaign's budget - a read. The fix replaced that with "does
 * this look like a read", inverted, which put the read test first by
 * construction and left the same hole one layer along: Meta names tools
 * `ads_<resource>_<verb>_<thing>`, so a name can carry both verbs, and
 * `ads_get_or_create_audience` matched `ads_get_` and was sent as a read.
 *
 * Mutating verbs are now checked before the read tests. These pin both halves:
 * that the classification actually reaches the kill switch, and that a name
 * carrying both verbs resolves to a write.
 */
class TheMcpKillSwitchCannotBeSlippedTest extends TestCase
{
    use RefreshDatabase;

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

        config([
            'platforms.guardrails.allowed_ad_accounts' => ['meta:*'],
            'platforms.guardrails.paused' => false,
        ]);
    }

    private function mcp(): AdsMcp
    {
        return new AdsMcp('mcp-test-token', 'https://mcp.facebook.com/ads', app(CallLogger::class));
    }

    /** Meta answers on a `data:` line rather than as a plain body. */
    private function fakeMeta(array $payload = ['ok' => true]): void
    {
        Http::fake([
            'mcp.facebook.com/*' => Http::response(
                'data: '.json_encode([
                    'jsonrpc' => '2.0',
                    'id' => 1,
                    'result' => ['content' => [['type' => 'text', 'text' => json_encode($payload)]]],
                ]),
                200,
                ['Content-Type' => 'text/event-stream'],
            ),
        ]);
    }

    /** True when the private classifier calls this tool a write. */
    private function classifiedAsWrite(string $tool): bool
    {
        $method = new ReflectionMethod(AdsMcp::class, 'writes');
        $method->setAccessible(true);

        return (bool) $method->invoke(null, $tool);
    }

    // ------------------------------------------------- the switch really bites

    public function test_an_ad_set_update_logs_the_url_payload_and_raw_response(): void
    {
        $logged = null;
        Log::listen(function (MessageLogged $log) use (&$logged): void {
            if ($log->message === 'Meta ads_update_entity') {
                $logged = $log;
            }
        });
        $this->fakeMeta(['success' => true]);

        $this->mcp()->updateEntity('act_111', '120252863619250100', 'ad_set', [
            'bid_amount' => 200,
            'bid_strategy' => 'COST_CAP',
        ]);

        $this->assertInstanceOf(MessageLogged::class, $logged);
        $encoded = json_encode($logged->context);
        $this->assertSame('info', $logged->level);
        $this->assertSame('https://mcp.facebook.com/ads', $logged->context['url']);
        $this->assertSame('ads_update_entity', $logged->context['payload']['params']['name']);
        $this->assertSame('120252863619250100', $logged->context['payload']['params']['arguments']['entity_id']);
        $this->assertStringContainsString('"bid_amount":200', (string) $logged->context['payload']['params']['arguments']['fields']);
        $this->assertSame(200, $logged->context['status']);
        $this->assertStringContainsString('data: ', (string) $logged->context['response']);
        $this->assertStringContainsString('success', (string) $logged->context['response']);
        $this->assertStringNotContainsString('mcp-test-token', (string) $encoded);
    }

    /** The guarantee itself: a write is refused and never reaches Meta. */
    public function test_the_kill_switch_stops_a_write_before_it_is_sent(): void
    {
        config(['platforms.guardrails.paused' => true]);
        $this->fakeMeta();

        $this->expectException(MetaException::class);
        $this->expectExceptionMessage('currently paused');

        try {
            $this->mcp()->updateEntity('act_111', '123', 'campaign', ['status' => 'PAUSED']);
        } finally {
            Http::assertNothingSent();
        }
    }

    /** And a read still works, so the product can keep explaining itself. */
    public function test_the_kill_switch_leaves_reads_alone(): void
    {
        config(['platforms.guardrails.paused' => true]);
        $this->fakeMeta(['ad_accounts' => [['id' => 'act_111']]]);

        $this->assertSame([['id' => 'act_111']], $this->mcp()->adAccounts());
    }

    // ------------------------------------------------------- the classification

    /**
     * The hole this fix is for.
     *
     * Reflection rather than a call, because there is no public entry point
     * for an arbitrary tool name - every caller goes through a named wrapper.
     * The test above proves the classification reaches the kill switch; this
     * one proves the classification itself is right for a name that carries a
     * read verb and a write verb at once.
     */
    public function test_a_name_carrying_both_verbs_is_a_write(): void
    {
        $this->assertTrue($this->classifiedAsWrite('ads_get_or_create_audience'));
        $this->assertTrue($this->classifiedAsWrite('ads_get_and_update_entity'));
        $this->assertTrue($this->classifiedAsWrite('ads_list_or_create_feed'));
    }

    /** Every tool this class actually sends, classified the way it must be. */
    public function test_the_tools_we_send_are_classified_correctly(): void
    {
        $writes = [
            'ads_create_campaign', 'ads_create_ad_set', 'ads_create_ad',
            'ads_create_creative', 'ads_update_entity', 'ads_creative_delete',
            'ads_activate_entity',
        ];

        $reads = ['ads_get_ad_accounts', 'ads_insights_anomaly_signal', 'ads_library_search'];

        foreach ($writes as $tool) {
            $this->assertTrue($this->classifiedAsWrite($tool), "{$tool} would skip the kill switch");
        }

        foreach ($reads as $tool) {
            $this->assertFalse($this->classifiedAsWrite($tool), "{$tool} would be refused while paused");
        }
    }

    /** A tool nobody has seen is dangerous until somebody says otherwise. */
    public function test_an_unknown_tool_is_treated_as_a_write(): void
    {
        $this->assertTrue($this->classifiedAsWrite('ads_whatever_meta_ships_next'));
    }
}
