#!/usr/bin/env php
<?php
/**
 * 二次风控 wait 日志：同步完整落库 + f_check UPDATE 不覆盖首段字段
 */
if (PHP_SAPI !== 'cli') {
    exit(1);
}

$root = dirname(__DIR__);
require_once $root . '/cong.php';
require_once $root . '/lib/Cloak/VisitorApiAudit.php';
require_once $root . '/lib/Cloak/VisitorVisitContext.php';
require_once $root . '/lib/Cloak/VisitorRepository.php';
require_once $root . '/lib/Cloak/VisitorLogWorker.php';
require_once $root . '/lib/Cloak/FCheckHandler.php';
require_once $root . '/lib/Cloak/PipelineTimer.php';

$tests = [];

// wait 路径应走 insertFull（源码约定）
$repoSrc = file_get_contents($root . '/lib/Cloak/VisitorRepository.php');
$tests['wait_uses_sync_full'] = strpos($repoSrc, 'cloak_write_log_db_wait_sync') !== false
    && strpos($repoSrc, "if (\$result === 'wait')") !== false
    && strpos($repoSrc, 'insertMinimal($logs)') === false;

$_SESSION = [];
$_SERVER['HTTP_USER_AGENT']      = 'VerifyWaitUA/1.0';
$_SERVER['HTTP_REFERER']         = 'https://referer.example/ads';
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'en-US,en;q=0.9';
$GLOBALS['__cloak_judge_timing'] = '{"total_ms":12.5,"stages":[{"name":"API","ms":8}]}';
VisitorApiAudit::recordByApiRequest(['id' => 'camp', 'ip' => '203.0.113.9']);
VisitorApiAudit::recordByApiResponse(['result' => true, 'reason' => '']);

$waitLogs = [
    'campagin_id'     => 'wait_verify',
    'visit_md5_code'  => 'wait_' . substr(md5((string) microtime(true)), 0, 12),
    'site_name'       => 'wait.test',
    'customers_ip'    => '203.0.113.9',
    'country'         => 'US',
    'result'          => 'wait',
    'reason'          => '二次风控检测中',
    'v_referer'       => 'https://referer.example/ads',
    'Client'          => 'PC',
    'v_Browser'       => 'chrome',
    'v_PageURL'       => 'https://wait.test/landing?utm=1',
    'accept_language' => 'English',
    'fp_url'          => '',
    'device'          => 'PC',
];
$GLOBALS['__cloak_force_sync_log'] = true;
$waitId = write_log_db($waitLogs);
unset($GLOBALS['__cloak_force_sync_log']);

$tests['wait_insert_returns_id'] = $waitId !== null && (int) $waitId > 0;

if ($waitId) {
    $conn = @new mysqli('localhost', DB_USERNAME, DB_PASSWORD, DB_NAME);
    if ($conn && !$conn->connect_error) {
        $res = $conn->query('SELECT `page`, `user_agent`, `http_referer`, `accept_language_raw`, `judge_timing`, `api_by_request`, `api_by_response`, `result` FROM `visitor_logs` WHERE `id`=' . (int) $waitId . ' LIMIT 1');
        $row = $res ? $res->fetch_assoc() : null;
        if ($row) {
            $tests['wait_has_page']        = trim((string) $row['page']) !== '';
            $tests['wait_has_user_agent']  = trim((string) $row['user_agent']) !== '';
            $tests['wait_has_referer']     = trim((string) $row['http_referer']) !== '';
            $tests['wait_has_timing']      = trim((string) $row['judge_timing']) !== '';
            $tests['wait_has_api_by_req']  = trim((string) $row['api_by_request']) !== '';
            $tests['wait_has_api_by_resp'] = trim((string) $row['api_by_response']) !== '';
            $tests['wait_result_is_wait']  = ($row['result'] ?? '') === 'wait';
        }

        VisitorVisitContext::bindLogId((int) $waitId);
        FCheckHandler::updateLog((int) $waitId, [
            'result' => 'true',
            'reason' => '',
            'fp_url' => 'https://fp.example/page',
        ], ['ip' => '203.0.113.9'], ['id' => 'camp'], ['result' => true], true);

        $res2 = $conn->query('SELECT `page`, `user_agent`, `judge_timing`, `api_by_request`, `result`, `fp_url` FROM `visitor_logs` WHERE `id`=' . (int) $waitId . ' LIMIT 1');
        $row2 = $res2 ? $res2->fetch_assoc() : null;
        if ($row2) {
            $tests['after_fcheck_keeps_page']       = trim((string) $row2['page']) === trim((string) $row['page']);
            $tests['after_fcheck_keeps_user_agent'] = trim((string) $row2['user_agent']) === trim((string) $row['user_agent']);
            $tests['after_fcheck_keeps_timing']     = trim((string) $row2['judge_timing']) === trim((string) $row['judge_timing']);
            $tests['after_fcheck_keeps_api_by']     = trim((string) $row2['api_by_request']) === trim((string) $row['api_by_request']);
            $tests['after_fcheck_updates_result']   = ($row2['result'] ?? '') === 'true';
            $tests['after_fcheck_updates_fp_url']   = strpos((string) $row2['fp_url'], 'fp.example') !== false;
        }

        $conn->query('DELETE FROM `visitor_logs` WHERE `id`=' . (int) $waitId);
        $conn->close();
    }
}

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