<?php
/**
 * AJAX endpoint: Test a specific AI provider connection.
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../ai/provider_engine.php';

$provider = strtolower(trim($_POST['provider'] ?? $_GET['provider'] ?? ''));
$allowed  = ['claude', 'groq', 'gemini', 'openai'];

if (!in_array($provider, $allowed, true)) {
    echo json_encode(['success' => false, 'error' => 'Invalid provider']);
    exit;
}

$start = microtime(true);

// Temporarily run only the requested provider
$original_providers = new ReflectionProperty(RBCAIEngine::class, 'providers');
$original_providers->setAccessible(true);
$saved = $original_providers->getValue();

// We can't dynamically change private static easily, so just try calling via generate
// with a minimal prompt; if it succeeds the provider is working
$result = RBCAIEngine::generate(
    'Reply with the single word: OK',
    'You are a test assistant. Reply with exactly one word.',
    20,
    false
);

$elapsed_ms = (int) round((microtime(true) - $start) * 1000);

// Check if the responding provider is the one we want
if ($result['success'] && $result['provider'] === $provider) {
    echo json_encode([
        'success'          => true,
        'provider'         => $provider,
        'response_time_ms' => $elapsed_ms,
        'response'         => trim($result['content']),
    ]);
} elseif (!$result['success']) {
    echo json_encode([
        'success'  => false,
        'provider' => $provider,
        'error'    => $result['error'] ?? 'Provider test failed',
        'response_time_ms' => $elapsed_ms,
    ]);
} else {
    // A different provider responded — the target provider may not be configured
    // Do a direct single-provider test
    $test_result = testSingleProvider($provider);
    $elapsed_ms2 = (int) round((microtime(true) - $start) * 1000);
    echo json_encode(array_merge($test_result, ['response_time_ms' => $elapsed_ms2]));
}

function testSingleProvider(string $provider): array
{
    $prompt  = 'Reply with the single word: OK';
    $system  = 'Reply with exactly one word.';

    switch ($provider) {
        case 'claude':
            $api_key = '';
            if (defined('CLAUDE_API_KEY') && CLAUDE_API_KEY !== 'YOUR_CLAUDE_API_KEY_HERE') {
                $api_key = CLAUDE_API_KEY;
            } else {
                $api_key = (string) getSettingValue('claude_api_key');
            }
            if (empty($api_key)) return ['success' => false, 'provider' => 'claude', 'error' => 'API key not configured'];
            $model = defined('CLAUDE_MODEL') ? CLAUDE_MODEL : 'claude-opus-4-5';
            $body = ['model' => $model, 'max_tokens' => 20, 'system' => $system, 'messages' => [['role' => 'user', 'content' => $prompt]]];
            $ch = curl_init('https://api.anthropic.com/v1/messages');
            curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($body),
                CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'x-api-key: ' . $api_key, 'anthropic-version: 2023-06-01'], CURLOPT_TIMEOUT => 15]);
            $resp = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
            $d = json_decode((string) $resp, true);
            if ($code === 200 && !empty($d['content'][0]['text'])) return ['success' => true, 'provider' => 'claude', 'response' => $d['content'][0]['text']];
            return ['success' => false, 'provider' => 'claude', 'error' => $d['error']['message'] ?? "HTTP $code"];

        case 'groq':
            $api_key = defined('GROQ_API_KEY') ? GROQ_API_KEY : (string) getSettingValue('groq_api_key');
            if (empty($api_key)) return ['success' => false, 'provider' => 'groq', 'error' => 'API key not configured'];
            $model = defined('GROQ_MODEL') ? GROQ_MODEL : 'llama-3.3-70b-versatile';
            $body = ['model' => $model, 'max_tokens' => 20, 'messages' => [['role' => 'system', 'content' => $system], ['role' => 'user', 'content' => $prompt]]];
            $ch = curl_init('https://api.groq.com/openai/v1/chat/completions');
            curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($body),
                CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Authorization: Bearer ' . $api_key], CURLOPT_TIMEOUT => 15]);
            $resp = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
            $d = json_decode((string) $resp, true);
            if ($code === 200 && !empty($d['choices'][0]['message']['content'])) return ['success' => true, 'provider' => 'groq', 'response' => $d['choices'][0]['message']['content']];
            return ['success' => false, 'provider' => 'groq', 'error' => $d['error']['message'] ?? "HTTP $code"];

        case 'gemini':
            $api_key = defined('GEMINI_API_KEY') ? GEMINI_API_KEY : (string) getSettingValue('gemini_api_key');
            if (empty($api_key)) return ['success' => false, 'provider' => 'gemini', 'error' => 'API key not configured'];
            $model = defined('GEMINI_MODEL') ? GEMINI_MODEL : 'gemini-2.0-flash';
            $body = ['contents' => [['role' => 'user', 'parts' => [['text' => $prompt]]]], 'generationConfig' => ['maxOutputTokens' => 20]];
            $ch = curl_init("https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$api_key}");
            curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($body), CURLOPT_HTTPHEADER => ['Content-Type: application/json'], CURLOPT_TIMEOUT => 15]);
            $resp = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
            $d = json_decode((string) $resp, true);
            $text = $d['candidates'][0]['content']['parts'][0]['text'] ?? null;
            if ($code === 200 && $text) return ['success' => true, 'provider' => 'gemini', 'response' => $text];
            return ['success' => false, 'provider' => 'gemini', 'error' => $d['error']['message'] ?? "HTTP $code"];

        case 'openai':
            $api_key = '';
            if (defined('OPENAI_API_KEY') && OPENAI_API_KEY) $api_key = OPENAI_API_KEY;
            elseif (defined('AI_OPENAI_API_KEY') && AI_OPENAI_API_KEY) $api_key = AI_OPENAI_API_KEY;
            else $api_key = (string) getSettingValue('openai_api_key');
            if (empty($api_key)) return ['success' => false, 'provider' => 'openai', 'error' => 'API key not configured'];
            $body = ['model' => 'gpt-4o-mini', 'max_tokens' => 20, 'messages' => [['role' => 'user', 'content' => $prompt]]];
            $ch = curl_init('https://api.openai.com/v1/chat/completions');
            curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($body),
                CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Authorization: Bearer ' . $api_key], CURLOPT_TIMEOUT => 15]);
            $resp = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
            $d = json_decode((string) $resp, true);
            if ($code === 200 && !empty($d['choices'][0]['message']['content'])) return ['success' => true, 'provider' => 'openai', 'response' => $d['choices'][0]['message']['content']];
            return ['success' => false, 'provider' => 'openai', 'error' => $d['error']['message'] ?? "HTTP $code"];
    }
    return ['success' => false, 'provider' => $provider, 'error' => 'Unknown provider'];
}
