<?php
/**
 * api/coraza-ai-explain.php — root-only AI explanation of a fired Coraza rule.
 * POST { rule_id, host? } + csrf_token.
 * Returns { ok, verdict, explanation, suggestion, context, 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;
}

$rule_id = (int)($_POST['rule_id'] ?? 0);
$host    = trim((string)($_POST['host'] ?? ''));
if ($rule_id < 1 || $rule_id > 9999999) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'invalid rule_id']);
    return;
}
if ($host !== '' && !preg_match('/^[a-z0-9._-]+$/i', $host)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'invalid host']);
    return;
}

$res = coraza_ai_explain_firing($rule_id, $host);
if (!$res['success']) {
    http_response_code(502);
    echo json_encode(['ok' => false, 'error' => $res['error']]);
    return;
}
echo json_encode([
    'ok'          => true,
    'verdict'     => $res['verdict'],
    'explanation' => $res['explanation'],
    'suggestion'  => $res['suggestion'],
    'context'     => $res['context'],
    'model'       => $res['model'],
]);
