<?php

namespace App\Controllers {
    class RoutingRedis
    {
        public static array $history = [];
        public static array $pending = [];

        public function get($key) { return self::$pending[$key] ?? null; }
        public function setex($key, $ttl, $value) { self::$pending[$key] = $value; return true; }
        public function del($key) { $exists = isset(self::$pending[$key]); unset(self::$pending[$key]); return (int) $exists; }
        public function exists($key) { return true; }
        public function hGet($key, $field)
        {
            return json_encode($field === 'dataList' ? self::$history : ($field === 'metadata' ? ['chatId' => '2'] : []));
        }
        public function hMSet($key, $values)
        {
            self::$history = json_decode($values['dataList'], true);
            return true;
        }
        public function expire($key, $ttl) { return true; }
        public function lRange($key, $start, $end) { return []; }
        public function rPush($key, $value) { return 1; }
    }

    function redis_connect_safe($host, $port) { return new RoutingRedis(); }
    function decrypt_str($value) { return $value; }
    function decryptData($value) { return $value; }
    function get_traffic_result(...$args) { return false; }
    function is_bot($agent) { return false; }
    function maxmindIp2location($ip) { return []; }
    function log_message($level, $message) { \RoutingProvider::$errors[] = $message; }
}

namespace App\Libraries {
    function log_message($level, $message) { \RoutingProvider::$errors[] = $message; }
}

namespace App\Models {
    class LibraryModel
    {
        public function checkTodayImageLimit(...$args) { return null; }
        public function addToDB($image) { return true; }
    }
}

namespace {
    use App\Controllers\RoutingRedis;
    use App\Controllers\SearchSSEController;
    use App\Libraries\AIManager;

    function helper($name) {}
    function check($condition, string $message): void
    {
        if (!$condition) {
            throw new \RuntimeException($message);
        }
    }

    class RoutingProvider
    {
        public static array $errors = [];
        public array $responses = [];
        public array $calls = [];

        public function classifyImageIntent($prompt, $hasImage, $previousPrompt, $reply)
        {
            $this->calls[] = [$prompt, $hasImage, $previousPrompt, $reply];
            $value = array_shift($this->responses);
            if ($value === null) {
                throw new \RuntimeException('Unexpected classification request');
            }
            return $value;
        }

        public function selectImageNumber($prompt, $imageCount)
        {
            $this->calls[] = ['selection', $prompt, $imageCount];
            return array_shift($this->responses) ?? 'none';
        }
    }

    $root = dirname(__DIR__) . '/';
    $temp = sys_get_temp_dir() . '/image-routing-' . bin2hex(random_bytes(6)) . '/';
    mkdir($temp, 0700);
    $fixtures = ['ai_response_track.php', 'encrypt_class.php', 'common.php'];
    try {
        foreach ($fixtures as $file) {
            file_put_contents($temp . $file, '<?php');
        }
        define('MSACOMMON_PATH', $temp);
        define('APPPATH', $root . 'app/');
        define('REDIS_HOST', 'test');
        define('REDIS_PORT', 0);
        require $root . 'vendor/autoload.php';
        require APPPATH . 'Libraries/AIManager.php';
        require APPPATH . 'Libraries/ChatAppearance.php';
        require APPPATH . 'Controllers/SearchSSEController.php';

        $provider = new RoutingProvider();
        $fallback = new RoutingProvider();
        $manager = new class extends AIManager {
            public array $generated = [];
            public function __construct() {}
            public function generateAIImage(string $prompt, $imagePath = '', ?string $maskPath = null)
            {
                $this->generated[] = $prompt;
                return ['image_url' => 'https://example.test/ai-images/generated.png', 'type' => 'Generate',
                    'ai_response' => '<img src="https://example.test/ai-images/generated.png">'];
            }
        };
        (new \ReflectionProperty(AIManager::class, 'providers'))->setValue($manager, ['OpenAI' => $provider, 'Gemini' => $fallback]);
        $controller = new class($manager) extends SearchSSEController {
            public AIManager $aiManager;
            public function __construct($manager)
            {
                $this->aiManager = $manager;
                $this->request = new class {
                    public function getGet($key = null)
                    {
                        $values = ['prompt' => 'Create a Sachin image', 'uid' => 1, 'auth' => 1, 'sub' => 1,
                            'currentChatId' => '2', 'isTemporaryChat' => 1, 'key' => '127.0.0.1',
                            'model' => 'openai'];
                        return $key === null ? $values : ($values[$key] ?? null);
                    }
                    public function getIPAddress() { return '127.0.0.1'; }
                    public function getUserAgent()
                    {
                        return new class {
                            public function getAgentString() { return 'test-browser'; }
                            public function isMobile() { return false; }
                        };
                    }
                };
            }
        };
        $resolve = new \ReflectionMethod(SearchSSEController::class, 'resolveChatImageRequest');
        $run = fn ($prompt, $parameters = []) => $resolve->invoke($controller, $prompt, 1, 2, 1, '', $parameters);
        $prompts = ['Maybelline', 'Where can I find tutorials for using Maybelline Sky High mascara?', 'cosmetics', 'cosmetics'];
        $history = [];
        foreach ($prompts as $prompt) {
            RoutingRedis::$history = $history;
            $provider->responses = ['clarify'];
            $provider->calls = [];
            $result = $run($prompt);
            check($result['intent'] === 'chat' && $result['prompt'] === $prompt, 'Text topics must not trigger image clarification');
            check(count($provider->calls) === 1 && $provider->calls[0][1] === false, 'Text thumbnails must not be image context');
            $history[] = ['action' => 'prompt', 'search' => $prompt,
                'response' => '<p>Text answer</p><img src="https://example.test/icon.png?next=/ai-images/example.png">'];
        }
        RoutingRedis::$history = $history;
        $provider->responses = ['generate'];
        $provider->calls = [];
        $result = $run('Create a Sachin image');
        check($result['intent'] === 'generate' && $result['prompt'] === 'Create a Sachin image', 'New image requests must retain their subject');
        check(count($provider->calls) === 1, 'Generation must bypass image selection');

        $generated = ['action' => 'prompt', 'search' => 'draw a cat', 'response' => '<img src="https://example.test/new.png">',
            'generated_image' => ['url' => 'https://example.test/new.png', 'type' => 'Generate']];
        RoutingRedis::$history = [$generated];
        $provider->responses = ['clarify'];
        check($run('cosmetics')['intent'] === 'clarify', 'Active generated images must still support clarification');
        $provider->responses = ['generate'];
        $result = $run('Create a Sachin image');
        check($result['intent'] === 'generate' && $result['prompt'] === 'Create a Sachin image', 'New image requests must cancel pending clarification');
        check(RoutingRedis::$pending === [], 'New image request must clear the pending choice');

        $provider->responses = ['clarify'];
        check($run('cosmetics')['intent'] === 'clarify', 'Clarification should be stored');
        $provider->responses = ['chat'];
        check($run('cosmetics')['intent'] === 'chat' && RoutingRedis::$pending === [], 'Repeated topic must cancel stale clarification');

        $provider->responses = ['clarify'];
        $run('cosmetics');
        $provider->responses = [];
        $result = $run('image');
        check($result['intent'] === 'generate' && $result['prompt'] === 'cosmetics', 'Format-only choices must use the original prompt');

        $provider->responses = ['clarify'];
        $run('cosmetics');
        $result = $run('text');
        check($result['intent'] === 'chat' && $result['prompt'] === 'cosmetics', 'Text choice must use the original prompt');

        RoutingRedis::$history = array_merge([$generated], $history);
        $provider->responses = ['clarify'];
        check($run('cosmetics')['intent'] === 'chat', 'Older generated images must not activate clarification after text');
        $provider->responses = ['edit', '1'];
        $result = $run('edit image 1');
        check($result['intent'] === 'edit' && $result['image']['url'] === 'https://example.test/new.png', 'Numbered image edits must still work');

        RoutingRedis::$history = [['search' => 'draw a dog', 'response' => '<img src="https://example.test/ai-images/legacy.png">']];
        $provider->responses = ['edit', 'none'];
        check($run('make it blue')['image']['url'] === 'https://example.test/ai-images/legacy.png', 'Legacy generated images must remain editable');
        check(!$manager->isImageIntentEligible(['is_canvas' => 'true']), 'Enabled special modes must be preserved');

        RoutingRedis::$history = $history;
        $provider->responses = ['invalid'];
        $fallback->responses = ['generate'];
        check($run('Create a Sachin image')['intent'] === 'generate', 'Gemini must handle failed OpenAI classification');
        check(count(RoutingProvider::$errors) === 1, 'Classification failure must be logged');
        $provider->responses = ['invalid'];
        $fallback->responses = ['invalid'];
        try {
            $run('Create a Sachin image');
            throw new \RuntimeException('Expected a classification failure');
        } catch (\RuntimeException $e) {
            check($e->getMessage() === 'Could not classify the image or text request.', 'Both-provider failure must surface explicitly');
        }

        $provider->responses = ['generate'];
        $controller->stream();
        check($manager->generated === ['Create a Sachin image'], 'SSE must call the image generator with the current request');
        $stored = RoutingRedis::$history[array_key_last(RoutingRedis::$history)];
        check($stored['generated_image']['url'] === 'https://example.test/ai-images/generated.png', 'Generated image identity must be persisted');
        echo "Chat image routing checks passed.\n";
    } finally {
        foreach ($fixtures as $file) {
            if (is_file($temp . $file)) {
                unlink($temp . $file);
            }
        }
        rmdir($temp);
    }
}
