#!/usr/bin/env php
<?php
/**
 * VisitorLogListHelper 回归（CLI JSON）
 */
if (PHP_SAPI !== 'cli') {
    exit(1);
}

$root = dirname(__DIR__);
require_once $root . '/cong.php';
require_once $root . '/lib/DbHelper.php';
require_once $root . '/lib/Cloak/VisitorLogListHelper.php';

$tests = [];

$conn = @new mysqli('localhost', DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE) . "\n";
    exit(1);
}

$where = VisitorLogListHelper::buildWhere($conn, ['visit_date' => '2026-01-15']);
$tests['date_range_where'] = strpos($where, 'visit_date') !== false && strpos($where, 'DATE_FORMAT') === false;

$whereAll = VisitorLogListHelper::buildWhere($conn, []);
$tests['default_includes_wait'] = strpos($whereAll, 'wait') === false;

$whereWait = VisitorLogListHelper::buildWhere($conn, ['result' => 'wait']);
$tests['filter_wait'] = strpos($whereWait, "`result` = 'wait'") !== false;

$whereWaitCn = VisitorLogListHelper::buildWhere($conn, ['result' => '检测中']);
$tests['filter_wait_cn'] = strpos($whereWaitCn, "`result` = 'wait'") !== false;

$sql = VisitorLogListHelper::listSelectSql('1', 0, 10, true);
$tests['lean_select_no_fp_hdata'] = strpos($sql, '`fp_hdata`,') === false && strpos($sql, 'has_fp_hdata') !== false;

$row = VisitorLogListHelper::formatListRow([
    'country' => 'US',
    'reason' => 'test',
    'result' => 'wait',
    'judge_timing' => '',
    'has_fp_hdata' => 1,
    'has_api_by_request' => 1,
], ['US' => '美国'], []);

$tests['format_wait'] = $row['result'] === '检测中';
$tests['format_lazy_api'] = $row['api_by_request_text'] === '__LAZY__';
$tests['format_fp_flag'] = $row['fp_hdata_text'] === '有指纹数据';
$tests['no_explain_html'] = !array_key_exists('fp_hdata_explain_html', $row);

$conn->close();

$ok = !in_array(false, $tests, true);
echo json_encode(['ok' => $ok, 'tests' => $tests], JSON_UNESCAPED_UNICODE) . "\n";
exit($ok ? 0 : 1);
