<?php
// Savit API: Get available AI models for platforms (Dynamic from DataForSEO)
// This file fetches the latest models from API and caches them in the DB.

header('Content-Type: application/json');

use CAE\Lib\Database;

$platform_label = $_GET['platform'] ?? 'ChatGPT';
$platform_map = [
    'ChatGPT' => 'chat_gpt',
    'Claude' => 'claude',
    'Gemini' => 'gemini',
    'Perplexity' => 'perplexity'
];
$platform_slug = $platform_map[$platform_label] ?? 'chat_gpt';

try {
    $db = Database::getInstance();
    
    // 1. Check if we have cached models for this platform updated in the last 24 hours
    $cached = $db->fetchAll(
        "SELECT model_name as name, label, is_latest FROM ai_research_models 
         WHERE platform = ? AND updated_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)
         ORDER BY is_latest DESC, id DESC",
        [$platform_slug]
    );

    if (empty($cached)) {
        // 2. Fetch from DataForSEO API
        $url = "https://api.dataforseo.com/v3/ai_optimization/{$platform_slug}/llm_responses/models";
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERPWD, DATAFORSEO_LOGIN . ":" . DATAFORSEO_PASSWORD);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($http_code === 200) {
            $api_data = json_decode((string)$response, true);
            $items = $api_data['tasks'][0]['result'] ?? [];
            
            if (!empty($items)) {
                $raw_models = [];
                foreach ($items as $item) {
                    if (isset($item['model_name'])) {
                        $raw_models[] = [
                            'name' => $item['model_name'],
                            'web_search_supported' => $item['web_search_supported'] ?? false
                        ];
                    }
                }

                // Sort ALL raw models to find the absolute latest across all versions
                uasort($raw_models, function($a, $b) use ($platform_slug) {
                    $nameA = strtolower($a['name']);
                    $nameB = strtolower($b['name']);
                    
                    // 1. Try to extract and compare dates (e.g. 2024-08-06)
                    preg_match('/(\d{4}-?\d{2}-?\d{2})/', $nameA, $d1);
                    preg_match('/(\d{4}-?\d{2}-?\d{2})/', $nameB, $d2);
                    $date1 = isset($d1[1]) ? (int)str_replace('-', '', $d1[1]) : 0;
                    $date2 = isset($d2[1]) ? (int)str_replace('-', '', $d2[1]) : 0;
                    
                    if ($date1 !== $date2) return $date2 <=> $date1;

                    // 2. Tiers (Higher = Better/Newer)
                    $getTier = function($name) {
                        $score = 0;
                        if (strpos($name, 'o1') !== false) $score = 100;
                        else if (strpos($name, 'opus') !== false) $score = 90;
                        else if (strpos($name, 'pro') !== false) $score = 80;
                        else if (strpos($name, 'sonnet') !== false) $score = 70;
                        else if (strpos($name, 'gpt') !== false) $score = 60;
                        else if (strpos($name, 'sonar') !== false) $score = 50;
                        
                        // Modifiers (Subtract priority)
                        if (strpos($name, 'mini') !== false) $score -= 40;
                        if (strpos($name, 'flash') !== false) $score -= 30;
                        if (strpos($name, 'haiku') !== false) $score -= 35;
                        if (strpos($name, 'lite') !== false) $score -= 45;
                        
                        return $score;
                    };

                    $t1 = $getTier($nameA);
                    $t2 = $getTier($nameB);

                    if ($platform_slug === 'gemini') {
                        if (strpos($nameA, 'pro') !== false && strpos($nameB, 'pro') === false) return -1;
                        if (strpos($nameB, 'pro') !== false && strpos($nameA, 'pro') === false) return 1;
                    }

                    // 3. Version numbers
                    preg_match('/(\d+(?:\.\d+)?)/', $nameA, $m1);
                    preg_match('/(\d+(?:\.\d+)?)/', $nameB, $m2);
                    $v1 = isset($m1[1]) ? (float)$m1[1] : 0;
                    $v2 = isset($m2[1]) ? (float)$m2[1] : 0;
                    
                    if ($v1 !== $v2) return $v2 <=> $v1;
                    if ($t1 !== $t2) return $t2 <=> $t1;
                    
                    // 4. Tie-breaker: Shorter name usually means base alias (preferred)
                    return strlen($nameA) <=> strlen($nameB);
                });

                // Clear old cache
                $db->delete('ai_research_models', 'platform = :p', ['p' => $platform_slug]);
                
                $models_to_return = [];
                $sorted_models = array_values($raw_models); // Reset keys so index 0 is first
                
                foreach ($sorted_models as $idx => $m) {
                    $is_latest = ($idx === 0) ? 1 : 0;
                    $label = $m['name'];
                    
                    // Human-friendly labels for common models
                    if (strpos($label, 'o1') !== false) $label = "o1 (Latest)";
                    else if (strpos($label, 'gpt-4o') !== false && strpos($label, 'mini') === false) $label = "GPT-4o (Latest)";
                    else if (strpos($label, 'gpt-4o-mini') !== false) $label = "GPT-4o mini (Latest)";
                    else if (strpos($label, 'claude-3-5-sonnet') !== false) $label = "Claude 3.5 Sonnet (Latest)";
                    else if (strpos($label, 'gemini-1.5-pro') !== false) $label = "Gemini 1.5 Pro (Latest)";

                    $db->insert('ai_research_models', [
                        'platform' => $platform_slug,
                        'model_name' => $m['name'],
                        'label' => $label,
                        'is_latest' => $is_latest
                    ]);
                    $models_to_return[] = ['name' => $m['name'], 'label' => $label, 'is_latest' => $is_latest];
                }
                $cached = $models_to_return;
            }
        }
    }

    // Fallback if needed (same as before)
    if (empty($cached)) {
        $fallback = [
            'chat_gpt' => [['name' => 'gpt-4o', 'label' => 'GPT-4o (Smartest)', 'is_latest' => 1]],
            'claude' => [['name' => 'claude-3-5-sonnet-20240620', 'label' => 'Claude 3.5 Sonnet', 'is_latest' => 1]],
            'gemini' => [['name' => 'gemini-1.5-pro', 'label' => 'Gemini 1.5 Pro', 'is_latest' => 1]],
            'perplexity' => [['name' => 'sonar-large-online', 'label' => 'Sonar Large (Online)', 'is_latest' => 1]]
        ];
        $cached = $fallback[$platform_slug] ?? [];
    }

    echo json_encode(['success' => true, 'models' => $cached]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}


