<?php
require_once dirname(__DIR__) . '/cong.php';
require_once dirname(__DIR__) . '/lib/bootstrap.php';
require_once dirname(__DIR__) . '/lib/Cloak/VisitorSimulationRunner.php';
session_start();

header('Content-Type: application/json; charset=utf-8');

if (empty($_SESSION['password']) || $_SESSION['password'] != LOGIN_PASSWORD) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'message' => '未授权'], JSON_UNESCAPED_UNICODE);
    exit;
}

$action = $_REQUEST['action'] ?? '';

if ($action === 'prefill') {
    $logId = (int) ($_GET['log_id'] ?? 0);
    echo json_encode(VisitorSimulationRunner::prefillFromLog($logId), JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'configs') {
    $list = [];
    foreach (glob(dirname(__DIR__) . '/check_config/*_config.php') as $file) {
        $name = basename($file, '_config.php');
        if ($name !== '') {
            $list[] = $name;
        }
    }
    sort($list);
    echo json_encode(['ok' => true, 'configs' => $list], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'message' => '请使用 POST'], JSON_UNESCAPED_UNICODE);
    exit;
}

$payload = $_POST;
if (empty($payload) && ($raw = file_get_contents('php://input'))) {
    $decoded = json_decode($raw, true);
    if (is_array($decoded)) {
        $payload = $decoded;
    }
}

if ($action === 'replay') {
    $logId = (int) ($payload['log_id'] ?? 0);
    echo json_encode(VisitorSimulationRunner::replayFromLog($logId), JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'run') {
    echo json_encode(VisitorSimulationRunner::runManual($payload), JSON_UNESCAPED_UNICODE);
    exit;
}

http_response_code(400);
echo json_encode(['ok' => false, 'message' => '未知 action'], JSON_UNESCAPED_UNICODE);
