<?php
/**
 * AI Manager for Finggu
 * Handles multi-AI providers with fallback logic
 */

function ai_generate_with_fallback($prompt, $pdo) {
    // Get all API keys
    $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM finggu_settings WHERE setting_key LIKE '%_api_key'");
    $stmt->execute();
    $allKeys = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

    // Priority list of providers
    $providers = [
        'gemini' => [
            'name' => 'Google Gemini',
            'enabled' => !empty($allKeys['gemini_api_key']),
            'function' => 'ai_provider_gemini'
        ],
        'groq' => [
            'name' => 'Groq (Llama 3.3)',
            'enabled' => !empty($allKeys['groq_api_key']),
            'function' => 'ai_provider_groq'
        ],
        'openrouter' => [
            'name' => 'OpenRouter',
            'enabled' => !empty($allKeys['openrouter_api_key']),
            'function' => 'ai_provider_openrouter'
        ],
        'mistral' => [
            'name' => 'Mistral AI',
            'enabled' => !empty($allKeys['mistral_api_key']),
            'function' => 'ai_provider_mistral'
        ],
        'together' => [
            'name' => 'Together AI',
            'enabled' => !empty($allKeys['together_api_key']),
            'function' => 'ai_provider_together'
        ],
        'cohere' => [
            'name' => 'Cohere',
            'enabled' => !empty($allKeys['cohere_api_key']),
            'function' => 'ai_provider_cohere'
        ]
    ];


    $errors = [];

    foreach ($providers as $id => $provider) {
        if (!$provider['enabled']) continue;

        try {
            $result = call_user_func($provider['function'], $prompt, $allKeys[$id . '_api_key']);
            if ($result) {
                return [
                    'success' => true,
                    'content' => $result,
                    'provider' => $provider['name']
                ];
            }
        } catch (Exception $e) {
            $errors[] = $provider['name'] . ": " . $e->getMessage();
        }
    }

    return [
        'success' => false,
        'error' => "All providers failed. Errors: " . implode(" | ", $errors)
    ];
}

/**
 * Google Gemini Provider
 */
function ai_provider_gemini($prompt, $apiKey) {
    $modelsToTry = ['gemini-2.0-flash', 'gemini-1.5-flash-latest', 'gemini-1.5-pro-latest'];
    
    foreach ($modelsToTry as $modelName) {
        $version = (strpos($modelName, 'latest') !== false) ? 'v1beta' : 'v1';
        $apiUrl = "https://generativelanguage.googleapis.com/$version/models/$modelName:generateContent?key=" . $apiKey;
        
        $data = [
            "contents" => [["parts" => [["text" => $prompt]]]]
        ];

        $ch = curl_init($apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode === 200) {
            $result = json_decode($response, true);
            $text = $result['candidates'][0]['content']['parts'][0]['text'] ?? '';
            if ($text) return $text;
        }
    }
    return null;
}

/**
 * Groq Provider (OpenAI Compatible)
 */
function ai_provider_groq($prompt, $apiKey) {
    return ai_openai_compatible_call(
        'https://api.groq.com/openai/v1/chat/completions',
        $apiKey,
        'llama-3.3-70b-versatile',
        $prompt
    );
}

/**
 * OpenRouter Provider (OpenAI Compatible)
 */
function ai_provider_openrouter($prompt, $apiKey) {
    return ai_openai_compatible_call(
        'https://openrouter.ai/api/v1/chat/completions',
        $apiKey,
        'google/gemini-2.0-flash-001', // Fallback to gemini if main openrouter choice is not set
        $prompt,
        ['HTTP-Referer' => 'https://finggu.com', 'X-Title' => 'Finggu']
    );
}

/**
 * Mistral AI Provider (OpenAI Compatible)
 */
function ai_provider_mistral($prompt, $apiKey) {
    return ai_openai_compatible_call(
        'https://api.mistral.ai/v1/chat/completions',
        $apiKey,
        'mistral-large-latest',
        $prompt
    );
}

/**
 * Together AI Provider (OpenAI Compatible)
 */
function ai_provider_together($prompt, $apiKey) {
    return ai_openai_compatible_call(
        'https://api.together.xyz/v1/chat/completions',
        $apiKey,
        'meta-llama/Llama-3.3-70B-Instruct-Turbo',
        $prompt
    );
}

/**
 * Cohere Provider (OpenAI Compatible)
 */
function ai_provider_cohere($prompt, $apiKey) {
    return ai_openai_compatible_call(
        'https://api.cohere.ai/v1/chat/completions',
        $apiKey,
        'command-r-plus',
        $prompt
    );
}


/**
 * Generic OpenAI Compatible API Call
 */
function ai_openai_compatible_call($url, $apiKey, $model, $prompt, $extraHeaders = []) {
    $data = [
        'model' => $model,
        'messages' => [
            ['role' => 'user', 'content' => $prompt]
        ],
        'temperature' => 0.7
    ];

    $headers = [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey
    ];

    foreach ($extraHeaders as $key => $val) {
        $headers[] = "$key: $val";
    }

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode === 200) {
        $result = json_decode($response, true);
        return $result['choices'][0]['message']['content'] ?? null;
    }
    
    return null;
}
