#!/usr/bin/env php
<?php
/**
 * 国家条件允许列表与 GeoIP 阶段开关回归
 */
if (PHP_SAPI !== 'cli') {
    exit(1);
}

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

$tests = [];

$tests['empty_disabled'] = CountryAllowlist::isEnabled('') === false;
$tests['whitespace_disabled'] = CountryAllowlist::isEnabled('  ,  ') === false;
$tests['us_enabled'] = CountryAllowlist::isEnabled('US') === true;
$tests['multi_enabled'] = CountryAllowlist::isEnabled('US,GB') === true;
$tests['empty_allow_all'] = CountryAllowlist::isAllowed('CN', []) === true;

$tests['cn_comma'] = CountryAllowlist::formatForConfig('US，GB ， CA') === 'US,GB,CA';
$tests['semicolon'] = CountryAllowlist::formatForConfig('US;GB;CA') === 'US,GB,CA';
$tests['cn_semicolon'] = CountryAllowlist::formatForConfig('US；GB；CN') === 'US,GB,CN';
$tests['dunhao'] = CountryAllowlist::formatForConfig('US、GB、CA') === 'US,GB,CA';
$tests['extra_spaces'] = CountryAllowlist::formatForConfig('  US ,  GB , CA  ') === 'US,GB,CA';
$tests['fullwidth_space'] = CountryAllowlist::formatForConfig("US\u{3000}，\u{3000}GB") === 'US,GB';
$tests['mixed_separators'] = CountryAllowlist::formatForConfig('US，GB;CN、AU') === 'US,GB,CN,AU';
$tests['duplicate_codes'] = CountryAllowlist::formatForConfig('US,us, US ,GB') === 'US,GB';
$tests['trailing_comma'] = CountryAllowlist::formatForConfig('US,GB,') === 'US,GB';
$tests['lowercase'] = CountryAllowlist::formatForConfig('us,gb,ca') === 'US,GB,CA';
$tests['mixed_case'] = CountryAllowlist::formatForConfig('Us ， gB ; cN') === 'US,GB,CN';
$tests['is_allowed_lower_visitor'] = CountryAllowlist::isAllowed('us', CountryAllowlist::parse('US,GB')) === true;
$tests['resolved_config'] = CountryAllowlist::formatForConfig('us,gb') === CountryAllowlist::resolvedConfig('us,gb');

$stage = file_get_contents($root . '/lib/Cloak/Pipeline/stages/check_country_geoip.inc.php');
$tests['stage_skips_when_disabled'] = strpos($stage, 'CountryAllowlist::isEnabled()') !== false;

$pipeline = file_get_contents($root . '/lib/Cloak/Pipeline/CheckPipeline.php');
$tests['pipeline_conditional_geo'] = strpos($pipeline, 'CountryAllowlist::isEnabled()') !== false;

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