<?php

namespace Tests\Feature;

use App\Agent\Instructions;
use App\Agent\MarketingAgent;
use App\Agent\NamespacedTool;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request as HttpRequest;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Approvals\PendingApproval;
use Laravel\Ai\Contracts\Providers\TextProvider;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Exceptions\RateLimitedException;
use Laravel\Ai\Exceptions\StreamErrorException;
use Laravel\Ai\Messages\AssistantMessage;
use Laravel\Ai\Messages\ToolResultMessage;
use Laravel\Ai\Messages\UserMessage;
use Laravel\Ai\Responses\AgentResponse;
use Laravel\Ai\Responses\Data\Meta;
use Laravel\Ai\Responses\Data\ToolCall as ToolCallData;
use Laravel\Ai\Responses\Data\ToolResult;
use Laravel\Ai\Responses\Data\Usage;
use Laravel\Ai\Responses\StreamableAgentResponse;
use Laravel\Ai\Streaming\Events\Error;
use Laravel\Ai\Streaming\Events\TextDelta;
use Laravel\Ai\Streaming\Events\ToolApprovalRequest;
use Laravel\Ai\Streaming\Events\ToolCall;
use Laravel\Ai\Tools\Request as ToolRequest;
use Mockery;
use PHPUnit\Framework\Attributes\DataProvider;
use RuntimeException;
use Tests\TestCase;

class ChatProviderFailoverTest extends TestCase
{
    use RefreshDatabase;

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

        $this->actingAs(User::factory()->create());
        config([
            'ai.conversations.generate_title' => false,
            'ai.gemini_api_enabled' => true,
            'ai.text_failover' => ['openai', 'gemini'],
            'ai.providers.openai.key' => 'fake-openai-key',
            'ai.providers.gemini.key' => 'fake-gemini-key',
            'ai.providers.gemini.url' => 'https://gemini.test/v1beta/',
            'ai.providers.openai.models.text.default' => 'primary-model',
            'ai.providers.gemini.models.text.default' => 'backup-model',
        ]);
    }

    public static function responseModes(): array
    {
        return ['JSON' => [false], 'stream' => [true]];
    }

    #[DataProvider('responseModes')]
    public function test_billing_failure_uses_gemini_with_its_own_model_and_preserves_the_conversation(bool $stream): void
    {
        $attempts = [];
        MarketingAgent::fake(function (string $prompt, Collection $attachments, TextProvider $provider, string $model) use (&$attempts): string {
            $attempts[] = [$provider->name(), $model, $prompt];

            if ($provider->name() === 'openai') {
                throw $this->billingFailure();
            }

            return 'Here is the requested review.';
        });

        $reply = $this->send($stream);

        $this->assertSame(['openai', 'gemini'], array_column($attempts, 0));
        $this->assertSame(['primary-model', 'backup-model'], array_column($attempts, 1));
        $this->assertSame($attempts[0][2], $attempts[1][2]);
        $this->assertStringContainsString('Here is the requested review.', $reply['reply']);
        $this->assertStringContainsString('Gemini', $reply['reply']);
        $this->assertDatabaseCount('agent_conversations', 1);
        $this->assertSame(1, DB::table('agent_conversation_messages')->where('role', 'user')->count());
        $this->assertDatabaseHas('agent_conversation_messages', ['role' => 'assistant', 'content' => $reply['reply']]);
    }

    #[DataProvider('responseModes')]
    public function test_a_healthy_primary_does_not_call_the_backup(bool $stream): void
    {
        $providers = [];
        MarketingAgent::fake(function (string $prompt, Collection $attachments, TextProvider $provider) use (&$providers): string {
            $providers[] = $provider->name();

            return 'Primary response.';
        });

        $reply = $this->send($stream);

        $this->assertSame(['openai'], $providers);
        $this->assertStringNotContainsString('fallback AI provider', $reply['reply']);
    }

    #[DataProvider('responseModes')]
    public function test_a_disabled_backup_is_not_contacted(bool $stream): void
    {
        config(['ai.gemini_api_enabled' => false]);
        $providers = [];
        MarketingAgent::fake(function (string $prompt, Collection $attachments, TextProvider $provider) use (&$providers): never {
            $providers[] = $provider->name();

            throw $this->billingFailure();
        });

        $reply = $this->send($stream);

        $this->assertSame(['openai'], $providers);
        $this->assertStringContainsString('That step failed', $reply['reply']);
    }

    #[DataProvider('responseModes')]
    public function test_both_providers_failing_reports_failure_without_looping_back(bool $stream): void
    {
        $providers = [];
        MarketingAgent::fake(function (string $prompt, Collection $attachments, TextProvider $provider) use (&$providers): never {
            $providers[] = $provider->name();

            throw $this->billingFailure();
        });

        $reply = $this->send($stream);

        $this->assertSame(['openai', 'gemini'], $providers);
        $this->assertStringContainsString('That step failed', $reply['reply']);
        $this->assertStringNotContainsString('This reply used', $reply['reply']);
    }

    #[DataProvider('responseModes')]
    public function test_ordinary_errors_do_not_switch_providers(bool $stream): void
    {
        $attempts = 0;
        MarketingAgent::fake(function () use (&$attempts): never {
            $attempts++;

            throw new RuntimeException('Invalid campaign request.');
        });

        $this->send($stream);

        $this->assertSame(1, $attempts);
    }

    #[DataProvider('responseModes')]
    public function test_tool_activity_without_database_writes_prevents_replaying_a_turn(bool $stream): void
    {
        $inner = Mockery::mock(Tool::class);
        $inner->shouldReceive('handle')->once()->andReturn('Read-only result.');
        $tool = new NamespacedTool('test', $inner);
        $attempts = 0;
        MarketingAgent::fake(function () use ($tool, &$attempts): never {
            $attempts++;
            $tool->handle(new ToolRequest([]));

            throw RateLimitedException::forProvider('openai');
        });

        $this->send($stream);

        $this->assertSame(1, $attempts);
    }

    #[DataProvider('responseModes')]
    public function test_approval_preparation_prevents_replaying_a_turn(bool $stream): void
    {
        $tool = new NamespacedTool('test', Mockery::mock(Tool::class));
        $attempts = 0;
        MarketingAgent::fake(function () use ($tool, &$attempts): never {
            $attempts++;
            $tool->shouldRequestApproval(new ToolRequest([]));

            throw $this->billingFailure();
        });

        $this->send($stream);

        $this->assertSame(1, $attempts);
    }

    #[DataProvider('responseModes')]
    public function test_a_recorded_change_prevents_fallback(bool $stream): void
    {
        $attempts = 0;
        MarketingAgent::fake(function () use (&$attempts): never {
            $attempts++;
            Campaign::create([
                'user_id' => auth()->id(), 'name' => 'Only once', 'platform' => 'meta', 'status' => 'draft',
            ]);

            throw $this->billingFailure();
        });

        $this->send($stream);

        $this->assertSame(1, $attempts);
        $this->assertDatabaseCount('campaigns', 1);
    }

    public static function startedStreamEvents(): array
    {
        return [
            'text' => ['text'],
            'tool call' => ['tool'],
            'approval' => ['approval'],
        ];
    }

    #[DataProvider('startedStreamEvents')]
    public function test_partial_stream_output_or_a_tool_request_prevents_fallback(string $event): void
    {
        $agent = Mockery::mock(MarketingAgent::class, [
            app(ToolRegistry::class), app(Workspace::class), app(Instructions::class),
        ])->makePartial();
        $agent->shouldReceive('stream')->once()->andReturn(new StreamableAgentResponse('partial', function () use ($event): \Generator {
            yield match ($event) {
                'text' => new TextDelta('delta', 'message', 'Already started.', time()),
                'tool' => new ToolCall('tool', new ToolCallData('call_review', 'campaign__publish_campaign', []), time()),
                'approval' => new ToolApprovalRequest('approval', collect([new PendingApproval('call_review', 'campaign__publish_campaign', [], 'Publish?')]), time()),
            };

            throw $this->billingFailure();
        }));
        $this->app->instance(MarketingAgent::class, $agent);

        $content = $this->post(route('chat.send'), ['message' => 'Hello there'], ['Accept' => 'text/event-stream'])->streamedContent();

        if ($event === 'text') {
            $this->assertStringContainsString('Already started.', $content);
        }
        $this->assertStringContainsString('"type":"error"', $content);
        $this->assertStringContainsString('[DONE]', $content);
    }

    public function test_a_fallback_approval_resumes_once_on_its_recorded_provider_and_model(): void
    {
        $providers = [];
        MarketingAgent::fake(function (string $prompt, Collection $attachments, TextProvider $provider) use (&$providers): AgentResponse {
            $providers[] = $provider->name();

            if ($provider->name() === 'openai') {
                throw $this->billingFailure();
            }

            return (new AgentResponse('pause', '', new Usage, new Meta('gemini', 'backup-model')))
                ->withPendingApprovals(collect([new PendingApproval('call_review', 'campaign__publish_campaign', [], 'Publish?')]));
        });
        $paused = $this->send(false);
        $this->assertSame('call_review', $paused['awaiting_approval'][0]['id']);
        $this->assertSame(['openai', 'gemini'], $providers);
        $resumes = [];
        MarketingAgent::fake(function (string $prompt, Collection $attachments, TextProvider $provider, string $model) use (&$resumes): never {
            $resumes[] = [$provider->name(), $model];

            throw RateLimitedException::forProvider('gemini');
        });

        $reply = $this->postJson(route('chat.decide'), [
            'conversation' => $paused['conversation'],
            'decisions' => ['call_review' => true],
        ])->assertStatus(502)->assertJsonPath('ok', false)
            ->json('reply');

        $this->assertStringContainsString('An approved action may already have reached the platform. Read its current state before retrying.', $reply);
        $this->assertSame([['gemini', 'backup-model']], $resumes);
    }

    public function test_the_real_gemini_gateway_sends_compatible_schemas_for_every_chat_tool(): void
    {
        Http::preventStrayRequests();
        Http::fake([
            'https://gemini.test/*' => Http::response([
                'candidates' => [[
                    'content' => ['role' => 'model', 'parts' => [['text' => 'Ready.']]],
                    'finishReason' => 'STOP',
                ]],
            ]),
        ]);

        $response = app(MarketingAgent::class)->forParticipant(auth()->user())
            ->prompt('Schema compatibility check.', provider: 'gemini');

        $this->assertSame('Ready.', $response->text);
        Http::assertSentCount(1);
        Http::assertSent(function (HttpRequest $request): bool {
            $declarations = $request['tools'][0]['function_declarations'];
            $this->assertNotEmpty($declarations);
            $this->assertCompatibleGeminiSchema($declarations);

            return true;
        });
    }

    public static function historicalToolIds(): array
    {
        return [
            'Gemini history' => ['call_10418511637918995640', 'call_10418511637918995640', false],
            'OpenAI history' => ['fc_original_item', 'call_original_result', true],
        ];
    }

    #[DataProvider('historicalToolIds')]
    public function test_openai_replays_tool_history_without_foreign_item_ids_or_changed_call_ids(string $itemId, string $callId, bool $keepItemId): void
    {
        config(['ai.providers.openai.url' => 'https://openai.test/v1']);
        Http::preventStrayRequests();
        Http::fake([
            'https://openai.test/*' => Http::response([
                'id' => 'resp_history_check',
                'status' => 'completed',
                'output' => [[
                    'type' => 'message', 'role' => 'assistant', 'id' => 'msg_check',
                    'content' => [['type' => 'output_text', 'text' => 'Ready.', 'annotations' => []]],
                ]],
            ]),
        ]);
        $call = new ToolCallData($itemId, 'campaign__review_changes', [], resultId: $callId);
        $result = new ToolResult($itemId, 'campaign__review_changes', [], 'No pending changes.', resultId: $callId);
        $response = \Laravel\Ai\agent(messages: [
            new UserMessage('Review the campaign.'),
            new AssistantMessage('', collect([$call])),
            new ToolResultMessage(collect([$result])),
        ])->prompt('Diagnostic check only. Do not call tools.', provider: 'openai');

        $this->assertSame('Ready.', $response->text);
        $this->assertSame($itemId, $call->id);
        $this->assertSame($callId, $result->resultId);
        Http::assertSentCount(1);
        Http::assertSent(function (HttpRequest $request) use ($itemId, $callId, $keepItemId): bool {
            $input = collect($request['input']);
            $function = $input->firstWhere('type', 'function_call');
            $output = $input->firstWhere('type', 'function_call_output');
            $this->assertSame($callId, $function['call_id']);
            $this->assertSame($callId, $output['call_id']);
            $this->assertSame('No pending changes.', $output['output']);

            if ($keepItemId) {
                $this->assertSame($itemId, $function['id']);
            } else {
                $this->assertArrayNotHasKey('id', $function);
            }

            return true;
        });
    }

    public function test_openai_replays_repeated_reasoning_once_without_dropping_tool_calls(): void
    {
        config(['ai.providers.openai.url' => 'https://openai.test/v1']);
        Http::preventStrayRequests();
        Http::fake([
            'https://openai.test/*' => Http::response([
                'id' => 'resp_history_check',
                'status' => 'completed',
                'output' => [[
                    'type' => 'message', 'role' => 'assistant', 'id' => 'msg_check',
                    'content' => [['type' => 'output_text', 'text' => 'Ready.', 'annotations' => []]],
                ]],
            ]),
        ]);
        $first = new ToolCallData('fc_first', 'campaign__review_changes', [], reasoningId: 'rs_same', reasoningSummary: []);
        $second = new ToolCallData('fc_second', 'campaign__review_changes', [], reasoningId: 'rs_same', reasoningSummary: []);

        \Laravel\Ai\agent(messages: [
            new UserMessage('Review the campaign.'),
            new AssistantMessage('', collect([$first])),
            new ToolResultMessage(collect([new ToolResult('fc_first', 'campaign__review_changes', [], 'First')])),
            new AssistantMessage('', collect([$second])),
            new ToolResultMessage(collect([new ToolResult('fc_second', 'campaign__review_changes', [], 'Second')])),
        ])->prompt('Continue.', provider: 'openai');

        Http::assertSent(function (HttpRequest $request): bool {
            $input = collect($request['input']);
            $this->assertCount(1, $input->where('type', 'reasoning')->where('id', 'rs_same'));
            $this->assertCount(2, $input->where('type', 'function_call'));
            $this->assertCount(2, $input->where('type', 'function_call_output'));

            return true;
        });
    }

    /** @param array<string|int, mixed> $node */
    private function assertCompatibleGeminiSchema(array $node): void
    {
        $this->assertArrayNotHasKey('additionalProperties', $node);

        if (($node['type'] ?? null) === 'array') {
            $this->assertArrayHasKey('items', $node);
        }

        if (($node['type'] ?? null) === 'object') {
            $this->assertNotEmpty($node['properties'] ?? []);
        }

        foreach ($node as $value) {
            if (is_array($value)) {
                $this->assertCompatibleGeminiSchema($value);
            }
        }
    }

    private function billingFailure(): StreamErrorException
    {
        return new StreamErrorException(new Error(
            'billing', 'error', 'Your account is not active, please check your billing details on our website.', false, time(),
        ));
    }

    /** @return array<string, mixed> */
    private function send(bool $stream): array
    {
        if (! $stream) {
            return $this->postJson(route('chat.send'), ['message' => 'Hello there'])->assertOk()->json();
        }

        $content = $this->post(route('chat.send'), ['message' => 'Hello there'], ['Accept' => 'text/event-stream'])->streamedContent();
        $done = collect(explode("\n\n", $content))
            ->map(fn (string $line): mixed => json_decode(substr($line, 6), true))
            ->firstWhere('type', 'done');
        $this->assertNotNull($done);

        return $done;
    }
}
