<?php
/**
 * api/coraza-ai-search.php — root-only AI search across the CRS rule catalog.
 * POST { query } + csrf_token.
 * Returns { ok, ids, explanation, model }.
 */

require_once('/docker/whp/web/libs/permission_checker.php');
require_once('/docker/whp/web/libs/coraza-ai.php');

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'POST required']);
    return;
}
if (!validate_csrf_token()) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'CSRF']);
    return;
}
if (!is_root_user()) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'admin only']);
    return;
}

$query = (string)($_POST['query'] ?? '');
$res = coraza_ai_search_catalog($query);
if (!$res['success']) {
    http_response_code(502);
    echo json_encode(['ok' => false, 'error' => $res['error']]);
    return;
}
echo json_encode([
    'ok'          => true,
    'ids'         => $res['ids'],
    'explanation' => $res['explanation'],
    'model'       => $res['model'],
]);
