<?php
declare(strict_types=1);

require __DIR__ . '/common.php';
$env = gobao_load_env();
gobao_require_admin($env);

function gobao_audit_summary(): array {
    $db = gobao_db();
    if (!$db) {
        return ['enabled' => false, 'error' => gobao_db_last_error()];
    }
    $summary = [
        'enabled' => true,
        'database' => gobao_db_counts(),
        'eventsByType' => [],
        'toolRunsByStatus' => [],
        'recentErrors' => [],
        'usage' => [
            'tokenInput' => 0,
            'tokenOutput' => 0,
            'latencyMsAvg' => 0,
            'retryCount' => 0,
        ],
    ];
    foreach ($db->query('SELECT event_type, COUNT(*) AS n FROM audit_events GROUP BY event_type ORDER BY n DESC')->fetchAll(PDO::FETCH_ASSOC) ?: [] as $row) {
        $summary['eventsByType'][(string)$row['event_type']] = (int)$row['n'];
    }
    foreach ($db->query('SELECT status, COUNT(*) AS n FROM tool_runs GROUP BY status ORDER BY n DESC')->fetchAll(PDO::FETCH_ASSOC) ?: [] as $row) {
        $summary['toolRunsByStatus'][(string)$row['status']] = (int)$row['n'];
    }
    $usage = $db->query('SELECT SUM(token_input) AS ti, SUM(token_output) AS to2, AVG(NULLIF(latency_ms,0)) AS lm, SUM(retry_count) AS rc FROM audit_events')->fetch(PDO::FETCH_ASSOC) ?: [];
    $summary['usage'] = [
        'tokenInput' => (int)($usage['ti'] ?? 0),
        'tokenOutput' => (int)($usage['to2'] ?? 0),
        'latencyMsAvg' => (int)round((float)($usage['lm'] ?? 0)),
        'retryCount' => (int)($usage['rc'] ?? 0),
    ];
    $stmt = $db->prepare("SELECT * FROM audit_events WHERE status IN ('failed','error') OR error IS NOT NULL ORDER BY id DESC LIMIT 20");
    $stmt->execute();
    $summary['recentErrors'] = array_map('gobao_audit_from_row', $stmt->fetchAll(PDO::FETCH_ASSOC) ?: []);
    return $summary;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $action = trim((string)($_GET['action'] ?? 'recent'));
    if ($action === 'recent') {
        gobao_ok([
            'events' => gobao_audit_recent(
                (int)($_GET['limit'] ?? 80),
                trim((string)($_GET['eventType'] ?? '')),
                trim((string)($_GET['sessionId'] ?? ''))
            ),
            'summary' => gobao_audit_summary(),
        ]);
    }
    if ($action === 'summary') {
        gobao_ok(['summary' => gobao_audit_summary()]);
    }
    gobao_fail('Unsupported GET action', 400);
}

if ($method !== 'POST') {
    gobao_fail('POST required', 405);
}

$input = gobao_json_input();
$action = trim((string)($input['action'] ?? 'record'));

if ($action === 'record') {
    $event = gobao_audit_record(trim((string)($input['eventType'] ?? 'manual_event')), [
        'sessionId' => trim((string)($input['sessionId'] ?? '')),
        'actor' => trim((string)($input['actor'] ?? 'user')),
        'status' => trim((string)($input['status'] ?? 'ok')),
        'refType' => trim((string)($input['refType'] ?? '')),
        'refId' => trim((string)($input['refId'] ?? '')),
        'title' => trim((string)($input['title'] ?? 'manual audit event')),
        'payload' => is_array($input['payload'] ?? null) ? $input['payload'] : [],
        'tokenInput' => (int)($input['tokenInput'] ?? 0),
        'tokenOutput' => (int)($input['tokenOutput'] ?? 0),
        'latencyMs' => (int)($input['latencyMs'] ?? 0),
        'retryCount' => (int)($input['retryCount'] ?? 0),
        'error' => trim((string)($input['error'] ?? '')),
    ]);
    gobao_ok(['event' => $event, 'summary' => gobao_audit_summary()]);
}

gobao_fail('Unsupported action', 400);
