<?php
/**
 * GET /api/health.php
 * Health check endpoint — no auth, fast response
 * Used by monitoring tools, load balancers, uptime checks
 */

$status = [
    'ok' => true,
    'timestamp' => date('c'),
    'checks' => [],
];

// 1. DB connectivity
try {
    require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../engine/Kernel.php';
Kernel::handle(['auth' => false, 'public' => true]);
require_once __DIR__ . '/../engine/Logger.php';
    $r = db()->query("SELECT 1")->fetchColumn();
    $status['checks']['db'] = $r == 1 ? 'ok' : 'unhealthy';
} catch (Throwable $e) {
    $status['checks']['db'] = 'error: ' . substr($e->getMessage(), 0, 60);
    $status['ok'] = false;
}

// 2. Critical tables
try {
    $tables = ['users','sessions','wallet','ai_usage','platform_settings'];
    $existing = db()->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
    $missing = array_diff($tables, $existing);
    $status['checks']['tables'] = empty($missing) ? 'ok' : 'missing:' . implode(',', $missing);
    if ($missing) $status['ok'] = false;
} catch (Throwable $e) {
    $status['checks']['tables'] = 'error';
}

// 3. Writable dirs
$dirs = ['uploads/documents','uploads/profile','logs'];
$status['checks']['writable'] = 'ok';
foreach ($dirs as $d) {
    $full = __DIR__ . '/../' . $d;
    if (!is_dir($full) || !is_writable($full)) {
        $status['checks']['writable'] = "not_writable: $d";
        $status['ok'] = false;
        break;
    }
}

// 4. AI providers configured
$status['checks']['ai_keys'] = (defined('GEMINI_API_KEY') && GEMINI_API_KEY) ||
                                (defined('CLAUDE_API_KEY') && CLAUDE_API_KEY) ||
                                (defined('OPENAI_API_KEY') && OPENAI_API_KEY) ? 'ok' : 'no_keys';

http_response_code($status['ok'] ? 200 : 503);
echo json_encode($status, JSON_UNESCAPED_UNICODE);
