#!/usr/bin/env php
<?php
/**
 * Cookie 域推断与指纹 JS 选项回归（CLI JSON）
 */
if (PHP_SAPI !== 'cli') {
    exit(1);
}

$root = dirname(__DIR__);
require_once $root . '/lib/CloakHttpHelpers.php';

$tests = [];

$cases = [
    ['shop.example.com', '.example.com'],
    ['shop.example.com:443', '.example.com'],
    ['SHOP.Example.COM:8080', '.example.com'],
    ['shili.buzz', '.shili.buzz'],
    ['www.shili.buzz', '.shili.buzz'],
    ['a.b.shili.buzz', '.shili.buzz'],
    ['shop.foo.co.uk', '.foo.co.uk'],
    ['www.shop.foo.co.uk', '.foo.co.uk'],
    ['127.0.0.1', ''],
    ['[::1]', ''],
    ['localhost', ''],
    ['cloaka.test', ''],
    ['single', ''],
];

foreach ($cases as $i => $case) {
    $_SERVER['HTTP_HOST'] = $case[0];
    $tests['domain_' . $i] = cloak_fingerprint_cookie_domain() === $case[1];
}

$_SERVER['HTTP_HOST'] = 'shop.example.com';
$_SERVER['HTTPS'] = 'on';
$jsOpts = cloak_fingerprint_js_cookie_options();
$tests['js_opts_domain'] = ($jsOpts['domain'] ?? '') === '.example.com';
$tests['js_opts_secure_https'] = !empty($jsOpts['secure']);
$tests['js_opts_samesite'] = ($jsOpts['sameSite'] ?? '') === 'Lax';

$_SERVER['HTTPS'] = 'off';
unset($_SERVER['HTTP_X_FORWARDED_PROTO']);
$jsOptsHttp = cloak_fingerprint_js_cookie_options();
$tests['js_opts_no_secure_http'] = empty($jsOptsHttp['secure']);

if (!defined('CLOAK_COOKIE_DOMAIN')) {
    define('CLOAK_COOKIE_DOMAIN', '.fixed.buzz');
}
$_SERVER['HTTP_HOST'] = 'other.example.com';
$tests['config_override'] = cloak_fingerprint_cookie_domain() === '.fixed.buzz';

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