<?php

namespace Tests\Feature;

use App\Services\AI\TextProviderFailover;
use Laravel\Ai\AiManager;
use Tests\TestCase;

class AiTextModelsTest extends TestCase
{
    public function test_gemini_api_is_disabled_when_enable_flag_is_missing(): void
    {
        $processValue = getenv('GEMINI_API_ENABLED');
        $hadEnvironmentValue = array_key_exists('GEMINI_API_ENABLED', $_ENV);
        $environmentValue = $_ENV['GEMINI_API_ENABLED'] ?? null;
        $hadServerValue = array_key_exists('GEMINI_API_ENABLED', $_SERVER);
        $serverValue = $_SERVER['GEMINI_API_ENABLED'] ?? null;

        unset($_ENV['GEMINI_API_ENABLED'], $_SERVER['GEMINI_API_ENABLED']);
        putenv('GEMINI_API_ENABLED');

        try {
            $aiConfig = require config_path('ai.php');

            $this->assertFalse($aiConfig['gemini_api_enabled']);
            $this->assertNull($aiConfig['providers']['gemini']['key']);
            $this->assertSame(['openai'], $aiConfig['text_failover']);
        } finally {
            if ($processValue === false) {
                putenv('GEMINI_API_ENABLED');
            } else {
                putenv('GEMINI_API_ENABLED='.$processValue);
            }

            if ($hadEnvironmentValue) {
                $_ENV['GEMINI_API_ENABLED'] = $environmentValue;
            } else {
                unset($_ENV['GEMINI_API_ENABLED']);
            }

            if ($hadServerValue) {
                $_SERVER['GEMINI_API_ENABLED'] = $serverValue;
            } else {
                unset($_SERVER['GEMINI_API_ENABLED']);
            }
        }
    }

    public function test_text_providers_resolve_the_requested_models_for_each_tier(): void
    {
        $providers = TextProviderFailover::providers();
        $ai = app(AiManager::class);

        $this->assertSame(['openai'], $providers);
        $this->assertFalse(config('ai.gemini_api_enabled'));
        $this->assertNull(config('ai.providers.gemini.key'));

        $openAi = $ai->textProvider($providers[0]);
        $this->assertSame('gpt-6-sol', $openAi->defaultTextModel());
        $this->assertSame('gpt-6.1-sol', config('campaign-performance.text_model'));
        $this->assertSame('gpt-6-luna', $openAi->cheapestTextModel());
        $this->assertSame('gpt-6-astra', $openAi->smartestTextModel());

        $gemini = $ai->textProvider('gemini');
        $this->assertSame('gemini-3.8-flash', $gemini->defaultTextModel());
        $this->assertSame('gemini-3.5-flash-lite', $gemini->cheapestTextModel());
        $this->assertSame('gemini-3.1-pro-preview', $gemini->smartestTextModel());
    }
}
