<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
require_once dirname(__DIR__) . '/includes/claude_api.php';

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

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

function checkEngine(string $engine): array
{
    $testSystem = 'You are a test assistant. Reply with exactly: OK';
    $testUser   = 'Say OK';
    $start = microtime(true);
    try {
        $result = match($engine) {
            'claude' => callClaude($testSystem, $testUser, 10),
            'groq'   => callGroq($testSystem, $testUser, 10),
            'gemini' => callGemini($testSystem, $testUser, 10),
        };
        $latency = (int) round((microtime(true) - $start) * 1000);
        return [
            'status'  => 'online',
            'latency' => $latency . 'ms',
            'error'   => null,
        ];
    } catch (Exception $e) {
        return [
            'status'  => 'offline',
            'latency' => null,
            'error'   => $e->getMessage(),
        ];
    }
}

$results = [
    'claude'     => checkEngine('claude'),
    'groq'       => checkEngine('groq'),
    'gemini'     => checkEngine('gemini'),
    'checked_at' => date('Y-m-d H:i:s'),
];

$onlineCount = 0;
foreach (['claude', 'groq', 'gemini'] as $e) {
    if (is_array($results[$e]) && ($results[$e]['status'] ?? '') === 'online') {
        $onlineCount++;
    }
}

$results['overall'] = match(true) {
    $onlineCount === 3 => 'all_online',
    $onlineCount >= 1  => 'degraded',
    default            => 'offline',
};

echo json_encode($results);
