#!/usr/bin/env bash
. "$(dirname "${BASH_SOURCE[0]}")/lib/harness.sh"
set -eo pipefail

PARSER_UC="$TACHYON_LIB/subscription/parser.uc"
GENERATOR_UC="$TACHYON_LIB/tachyon_core/generator.uc"
CACHE_UC="$TACHYON_LIB/subscription/cache.uc"

normalize_subscription() {
  local input="$1"
  local output="$2"
  ucode -L "$TACHYON_LIB" "$PARSER_UC" normalize-content "$input" "$output"
}

prepare_subscription_cache() {
  local section="$1"
  local index="$2"
  local url="$3"
  local normalized_json="$4"
  local source="$WORK_DIR/subscriptions/${section}-subscription-${index}"

  mkdir -p "$WORK_DIR/subscriptions"
  cp "$normalized_json" "${source}.json"
  printf '%s\n' "$url" >"${source}.url"
  : >"${source}.user_agent"
}

generate_config() {
  local fixture="$1"
  local output="$2"
  mkdir -p "${output}.section-cache"
  TMP_SUBSCRIPTION_FOLDER="$WORK_DIR/subscriptions" \
    ucode -L "$TACHYON_LIB" "$GENERATOR_UC" generate-config-fixture \
      "$fixture" "$output" "127.0.0.1"
}

cat >"$WORK_DIR/xray.json" <<'JSON'
{
  "remarks": "Latvia group",
  "burstObservatory": {
    "pingConfig": {
      "destination": "https://probe.example/204",
      "interval": "45s",
      "timeout": "3s",
      "sampling": 2
    }
  },
  "routing": {
    "balancers": [
      {
        "tag": "latvia-balancer",
        "selector": [ "lv-" ]
      }
    ]
  },
  "outbounds": [
    {
      "protocol": "vless",
      "tag": "lv-🇱🇻 Riga A",
      "settings": {
        "vnext": [
          {
            "address": "riga-a.example",
            "port": 443,
            "users": [
              {
                "id": "00000000-0000-4000-8000-000000000001",
                "encryption": "none"
              }
            ]
          }
        ]
      },
      "streamSettings": {
        "security": "tls",
        "tlsSettings": {
          "serverName": "riga-a.example"
        }
      }
    },
    {
      "protocol": "vless",
      "tag": "lv-🇱🇻 Riga B",
      "settings": {
        "vnext": [
          {
            "address": "riga-b.example",
            "port": 443,
            "users": [
              {
                "id": "00000000-0000-4000-8000-000000000002",
                "encryption": "none"
              }
            ]
          }
        ]
      },
      "streamSettings": {
        "security": "tls",
        "tlsSettings": {
          "serverName": "riga-b.example"
        }
      }
    }
  ]
}
JSON

xray_normalized="$WORK_DIR/xray-normalized.json"
normalize_subscription "$WORK_DIR/xray.json" "$xray_normalized"

ucode -e '
let fs = require("fs");
let value = json(fs.readfile(ARGV[0]));
let group = null;
for (let outbound in value.outbounds || [])
    if (outbound.type == "urltest")
        group = outbound;
if (!group)
    die("missing xray urltest group\n");
if (group.url != "https://probe.example/204")
    die("xray urltest url was not preserved\n");
if (group.interval != "45s")
    die("xray urltest interval was not preserved\n");
if (group.tolerance != null)
    die("xray urltest should not receive hardcoded tolerance\n");
for (let child in group.outbounds || [])
    if (substr(child, 0, 5) == "xray-")
        die("xray urltest child tags should preserve source names when unique\n");
' "$xray_normalized" || fail "xray normalized URLTest fields"

prepare_subscription_cache proxy 1 "https://xray.example/sub" "$xray_normalized"
cat >"$WORK_DIR/xray-fixture.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "log_level": "warn"
  },
  "section": [
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "proxy",
      "urltest_enabled": "1",
      "urltest_check_interval": "3m",
      "urltest_tolerance": "50",
      "urltest_filter_mode": "include",
      "urltest_include_regex": [ "Riga" ],
      "detect_server_country": "flag_emoji",
      "subscription_urls": [ "https://xray.example/sub" ]
    }
  ]
}
JSON

xray_config="$WORK_DIR/xray-config.json"
generate_config "$WORK_DIR/xray-fixture.json" "$xray_config"

cat >"$WORK_DIR/xray-reveal-urltest-fixture.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "log_level": "warn"
  },
  "section": [
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "proxy",
      "urltest_enabled": "1",
      "urltest_check_interval": "3m",
      "urltest_tolerance": "50",
      "urltest_filter_mode": "include",
      "urltest_include_regex": [ "Riga" ],
      "detect_server_country": "flag_emoji",
      "subscription_urls": [ "https://xray.example/sub" ],
      "subscription_url_settings": "{\"https://xray.example/sub\":{\"hide_urltest_group_outbounds\":\"0\"}}"
    }
  ]
}
JSON

xray_reveal_urltest_config="$WORK_DIR/xray-reveal-urltest-config.json"
generate_config "$WORK_DIR/xray-reveal-urltest-fixture.json" "$xray_reveal_urltest_config"

cat >"$WORK_DIR/xray-group-name-filter-fixture.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "log_level": "warn"
  },
  "section": [
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "proxy",
      "urltest_enabled": "1",
      "urltest_check_interval": "3m",
      "urltest_tolerance": "50",
      "urltest_filter_mode": "include",
      "urltest_include_outbounds": [ "Latvia group" ],
      "detect_server_country": "flag_emoji",
      "subscription_urls": [ "https://xray.example/sub" ],
      "subscription_url_settings": "{\"https://xray.example/sub\":{\"hide_urltest_group_outbounds\":\"0\"}}"
    }
  ]
}
JSON

xray_group_name_filter_config="$WORK_DIR/xray-group-name-filter-config.json"
generate_config "$WORK_DIR/xray-group-name-filter-fixture.json" "$xray_group_name_filter_config"

ucode -e '
let fs = require("fs");
function object_or_empty(value) { return type(value) == "object" ? value : {}; }
let config = json(fs.readfile(ARGV[0]));
let cache = json(fs.readfile(ARGV[1]));
let reveal_config = json(fs.readfile(ARGV[2]));
let group_name_filter_config = json(fs.readfile(ARGV[3]));
let imported = null;
let builtin = null;
let reveal_selector = null;
let group_name_builtin = null;
function contains(values, needle) {
    for (let value in values || [])
        if (value == needle)
            return true;
    return false;
}
for (let outbound in config.outbounds || []) {
    if (outbound.type == "urltest" && outbound.tag == "Latvia group")
        imported = outbound;
    if (outbound.type == "urltest" && outbound.tag == "proxy-urltest-out")
        builtin = outbound;
}
for (let outbound in reveal_config.outbounds || [])
    if (outbound.type == "selector" && outbound.tag == "proxy-out")
        reveal_selector = outbound;
for (let outbound in group_name_filter_config.outbounds || [])
    if (outbound.type == "urltest" && outbound.tag == "proxy-urltest-out")
        group_name_builtin = outbound;
if (!imported || imported.url != "https://probe.example/204" || imported.interval != "45s")
    die("generated xray imported URLTest did not preserve subscription params\n");
if (!builtin || length(builtin.outbounds || []) != 2)
    die("built-in URLTest should include two matched xray leaf outbounds\n");
for (let child in builtin.outbounds || [])
    if (child == "Latvia group")
        die("built-in URLTest must not use the xray group tag as a child\n");
if (group_name_builtin)
    die("built-in URLTest must not match subscription URLTest group names as servers\n");
for (let child in builtin.outbounds || [])
    if (substr(child, 0, 5) == "xray-")
        die("built-in URLTest must not use artificial xray child tag prefixes\n");
if (object_or_empty(cache.urltestGroups)["Latvia group"].url != "https://probe.example/204")
    die("section cache is missing imported xray URLTest params\n");
if (length(object_or_empty(cache.urltestGroups)["proxy-urltest-out"].outbounds || []) != 2)
    die("section cache is missing built-in URLTest membership\n");
let candidates = cache.urltestCandidateTags || [];
if (contains(candidates, "Latvia group") || contains(candidates, "proxy-urltest-out"))
    die("section cache URLTest candidates must not include URLTest groups\n");
if (length(candidates) != length(builtin.outbounds || []))
    die("section cache URLTest candidates should include only xray leaf outbounds\n");
for (let child in builtin.outbounds || [])
    if (!contains(candidates, child))
        die("section cache URLTest candidates are missing a matched xray leaf outbound\n");
if (!reveal_selector || length(reveal_selector.outbounds || []) != 4)
    die("xray URLTest children should become visible when subscription hiding is disabled\n");
' "$xray_config" "$xray_config.section-cache/proxy.json" "$xray_reveal_urltest_config" "$xray_group_name_filter_config" || fail "xray generated URLTest behavior"

xray_metadata="$WORK_DIR/xray-ui-outbound-metadata.json"
ucode -L "$TACHYON_LIB" "$CACHE_UC" get-outbound-metadata "$xray_config.section-cache" proxy "$WORK_DIR/missing-outbound-metadata.json" >"$xray_metadata"

ucode -e '
let fs = require("fs");
let metadata = json(fs.readfile(ARGV[0]));
let names = type(metadata.names) == "object" ? metadata.names : {};
if (names["Latvia group"] != null || names["proxy-urltest-out"] != null)
    die("UI outbound metadata must not include URLTest group names\n");
if (length(keys(names)) != 2)
    die("UI outbound metadata should contain only xray leaf outbound names\n");
' "$xray_metadata" || fail "xray UI outbound metadata filtering"

cat >"$WORK_DIR/core-sub.json" <<'JSON'
{
  "outbounds": [
    {
      "type": "urltest",
      "tag": "Native Group",
      "outbounds": [ "Native A" ],
      "url": "https://native.example/ping",
      "interval": "1m",
      "tolerance": 80
    },
    {
      "type": "vless",
      "tag": "Native A",
      "server": "native-a.example",
      "server_port": 443,
      "uuid": "00000000-0000-4000-8000-000000000003",
      "tls": {
        "enabled": true,
        "server_name": "native-a.example"
      }
    },
    {
      "type": "vless",
      "tag": "Detour Only",
      "server": "detour.example",
      "server_port": 443,
      "uuid": "00000000-0000-4000-8000-000000000004",
      "tls": {
        "enabled": true,
        "server_name": "detour.example"
      }
    },
    {
      "type": "vless",
      "tag": "Uses Detour",
      "server": "uses-detour.example",
      "server_port": 443,
      "uuid": "00000000-0000-4000-8000-000000000005",
      "detour": "Detour Only",
      "tls": {
        "enabled": true,
        "server_name": "uses-detour.example"
      }
    }
  ]
}
JSON

core_normalized="$WORK_DIR/core-normalized.json"
normalize_subscription "$WORK_DIR/core-sub.json" "$core_normalized"

ucode -e '
let fs = require("fs");
let value = json(fs.readfile(ARGV[0]));
let flags = {};
for (let outbound in value.outbounds || [])
    flags[outbound.tag] = {
        allow: outbound.__tachyon_allow_group === true,
        hidden: outbound.__tachyon_hidden === true
    };
if (!flags["Native Group"].allow)
    die("native core URLTest group was not allowed\n");
if (!flags["Native A"].hidden)
    die("native core URLTest child was not hidden\n");
if (!flags["Detour Only"].hidden)
    die("native core detour-only outbound was not hidden\n");
if (flags["Uses Detour"].hidden)
    die("visible outbound using detour should stay visible\n");
' "$core_normalized" || fail "native core normalized URLTest fields"

rm -rf "$WORK_DIR/subscriptions"
prepare_subscription_cache proxy 1 "https://sub.example.test/sub" "$core_normalized"
cat >"$WORK_DIR/core-fixture.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "log_level": "warn"
  },
  "section": [
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "proxy",
      "urltest_enabled": "1",
      "urltest_check_interval": "3m",
      "urltest_tolerance": "50",
      "urltest_filter_mode": "include",
      "urltest_include_regex": [ "^Native" ],
      "detect_server_country": "country_is",
      "subscription_urls": [ "https://sub.example.test/sub" ]
    }
  ]
}
JSON

core_config="$WORK_DIR/core-config.json"
generate_config "$WORK_DIR/core-fixture.json" "$core_config"

cat >"$WORK_DIR/core-prefix-fixture.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "log_level": "warn"
  },
  "section": [
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "proxy",
      "urltest_enabled": "1",
      "urltest_check_interval": "3m",
      "urltest_tolerance": "50",
      "urltest_filter_mode": "include",
      "urltest_include_regex": [ "^Provider " ],
      "detect_server_country": "country_is",
      "subscription_urls": [ "https://sub.example.test/sub" ],
      "subscription_url_settings": "{\"https://sub.example.test/sub\":{\"prefix_nodes\":\"1\",\"node_prefix\":\"Provider\"}}"
    }
  ]
}
JSON

core_prefix_config="$WORK_DIR/core-prefix-config.json"
generate_config "$WORK_DIR/core-prefix-fixture.json" "$core_prefix_config"

ucode -e '
let fs = require("fs");
function object_or_empty(value) { return type(value) == "object" ? value : {}; }
function outbound_by_tag(config, tag) {
    for (let outbound in config.outbounds || [])
        if (outbound && outbound.tag == tag)
            return outbound;
    return null;
}
function contains(values, needle) {
    for (let value in values || [])
        if (value == needle)
            return true;
    return false;
}
let config = json(fs.readfile(ARGV[0]));
let cache = json(fs.readfile(ARGV[1]));
let names = object_or_empty(object_or_empty(cache.outboundMetadata).names);
let groups = object_or_empty(cache.urltestGroups);
let imported = outbound_by_tag(config, "Provider Native Group");
let native = outbound_by_tag(config, "Provider Native A");
let detour = outbound_by_tag(config, "Provider Detour Only");
let uses_detour = outbound_by_tag(config, "Provider Uses Detour");
let builtin = outbound_by_tag(config, "proxy-urltest-out");
if (!imported || !native || !detour || !uses_detour)
    die("subscription prefix was not applied to every imported outbound\n");
if (length(imported.outbounds || []) != 1 || imported.outbounds[0] != "Provider Native A")
    die("subscription prefix did not rewrite imported URLTest group membership\n");
if (uses_detour.detour != "Provider Detour Only")
    die("subscription prefix did not rewrite detour references\n");
if (!builtin || length(builtin.outbounds || []) != 3)
    die("prefixed node names did not match the configured URLTest filter\n");
for (let tag in [ "Provider Native A", "Provider Detour Only", "Provider Uses Detour" ])
    if (!contains(builtin.outbounds, tag))
        die("built-in URLTest is missing a prefixed node\n");
if (contains(cache.urltestCandidateTags || [], "Provider Native Group"))
    die("prefixed imported URLTest group must not become a URLTest candidate\n");
if (object_or_empty(groups["Provider Native Group"]).displayName != "Provider Native Group")
    die("prefixed imported URLTest group display name was not retained\n");
if (names["Provider Native A"] != "Provider Native A" ||
    names["Provider Native Group"] != "Provider Native Group")
    die("prefixed outbound metadata names were not retained\n");
if (names["Native A"] != null || names["Native Group"] != null)
    die("unprefixed outbound metadata names must not remain\n");
' "$core_prefix_config" "$core_prefix_config.section-cache/proxy.json" || fail "subscription node prefix behavior"

cat >"$WORK_DIR/core-drop-urltest-members-fixture.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "log_level": "warn"
  },
  "section": [
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "proxy",
      "urltest_enabled": "0",
      "detect_server_country": "country_is",
      "subscription_urls": [ "https://sub.example.test/sub" ],
      "subscription_url_settings": "{\"https://sub.example.test/sub\":{\"include_urltest_groups\":\"0\"}}"
    }
  ]
}
JSON

core_drop_members_config="$WORK_DIR/core-drop-urltest-members-config.json"
generate_config "$WORK_DIR/core-drop-urltest-members-fixture.json" "$core_drop_members_config"

# With subscription URLTest groups switched off, the group is not emitted and
# the node it was the only reference to is unreachable, so it must not linger in
# the config either. Detour Only and Uses Detour are not group members and are
# the reason the section still has usable outbounds, so they must survive.
ucode -e '
let fs = require("fs");
function outbound_by_tag(config, tag) {
    for (let outbound in config.outbounds || [])
        if (outbound && outbound.tag == tag)
            return outbound;
    return null;
}
let config = json(fs.readfile(ARGV[0]));
if (outbound_by_tag(config, "Native Group"))
    die("a disabled subscription URLTest group must not be emitted\n");
if (outbound_by_tag(config, "Native A"))
    die("a node reachable only through a disabled URLTest group must be dropped\n");
if (!outbound_by_tag(config, "Detour Only"))
    die("a non-member outbound must survive the URLTest member filter\n");
if (!outbound_by_tag(config, "Uses Detour"))
    die("a non-member outbound using a detour must survive the filter\n");
' "$core_drop_members_config" || fail "disabled URLTest group members are dropped"

cat >"$WORK_DIR/core-reveal-urltest-fixture.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "log_level": "warn"
  },
  "section": [
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "proxy",
      "urltest_enabled": "1",
      "urltest_check_interval": "3m",
      "urltest_tolerance": "50",
      "urltest_filter_mode": "include",
      "urltest_include_regex": [ "^Native" ],
      "detect_server_country": "country_is",
      "subscription_urls": [ "https://sub.example.test/sub" ],
      "subscription_url_settings": "{\"https://sub.example.test/sub\":{\"hide_urltest_group_outbounds\":\"0\"}}"
    }
  ]
}
JSON

cat >"$WORK_DIR/core-reveal-detour-fixture.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "log_level": "warn"
  },
  "section": [
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "proxy",
      "urltest_enabled": "1",
      "urltest_check_interval": "3m",
      "urltest_tolerance": "50",
      "urltest_filter_mode": "include",
      "urltest_include_regex": [ "^Native" ],
      "detect_server_country": "country_is",
      "subscription_urls": [ "https://sub.example.test/sub" ],
      "subscription_url_settings": "{\"https://sub.example.test/sub\":{\"hide_detour_outbounds\":\"0\"}}"
    }
  ]
}
JSON

core_reveal_urltest_config="$WORK_DIR/core-reveal-urltest-config.json"
core_reveal_detour_config="$WORK_DIR/core-reveal-detour-config.json"
generate_config "$WORK_DIR/core-reveal-urltest-fixture.json" "$core_reveal_urltest_config"
generate_config "$WORK_DIR/core-reveal-detour-fixture.json" "$core_reveal_detour_config"

ucode -e '
let fs = require("fs");
function object_or_empty(value) { return type(value) == "object" ? value : {}; }
let config = json(fs.readfile(ARGV[0]));
let cache = json(fs.readfile(ARGV[1]));
let reveal_urltest_config = json(fs.readfile(ARGV[2]));
let reveal_detour_config = json(fs.readfile(ARGV[3]));
let imported = null;
let builtin = null;
let selector = null;
let reveal_urltest_selector = null;
let reveal_detour_selector = null;
for (let outbound in config.outbounds || []) {
    if (outbound.type == "urltest" && outbound.tag == "Native Group")
        imported = outbound;
    if (outbound.type == "urltest" && outbound.tag == "proxy-urltest-out")
        builtin = outbound;
    if (outbound.type == "selector" && outbound.tag == "proxy-out")
        selector = outbound;
}
for (let outbound in reveal_urltest_config.outbounds || [])
    if (outbound.type == "selector" && outbound.tag == "proxy-out")
        reveal_urltest_selector = outbound;
for (let outbound in reveal_detour_config.outbounds || [])
    if (outbound.type == "selector" && outbound.tag == "proxy-out")
        reveal_detour_selector = outbound;
function contains(values, needle) {
    for (let value in values || [])
        if (value == needle)
            return true;
    return false;
}
if (!imported || imported.url != "https://native.example/ping" || imported.interval != "1m" || imported.tolerance != 80)
    die("generated native URLTest did not preserve subscription params\n");
if (!builtin || length(builtin.outbounds || []) != 1 || builtin.outbounds[0] != "Native A")
    die("built-in URLTest regex filter should expand Native Group to Native A only\n");
for (let tag in selector.outbounds || [])
    if (tag == "Native A")
        die("native URLTest child must not be visible in selector by default\n");
for (let tag in selector.outbounds || [])
    if (tag == "Detour Only")
        die("detour-only outbound must not be visible in selector\n");
if (!reveal_urltest_selector || !contains(reveal_urltest_selector.outbounds, "Native A"))
    die("native URLTest child should be visible when URLTest hiding is disabled\n");
if (contains(reveal_urltest_selector ? reveal_urltest_selector.outbounds : [], "Detour Only"))
    die("detour outbound should stay hidden when only URLTest hiding is disabled\n");
if (contains(reveal_detour_selector ? reveal_detour_selector.outbounds : [], "Native A"))
    die("native URLTest child should stay hidden when only detour hiding is disabled\n");
if (!reveal_detour_selector || !contains(reveal_detour_selector.outbounds, "Detour Only"))
    die("detour outbound should be visible when detour hiding is disabled\n");
if (length(object_or_empty(cache.urltestGroups)["Native Group"].outbounds || []) != 1)
    die("section cache is missing native URLTest membership\n");
let candidates = cache.urltestCandidateTags || [];
if (contains(candidates, "Native Group") || contains(candidates, "proxy-urltest-out"))
    die("section cache native URLTest candidates must not include URLTest groups\n");
if (!contains(candidates, "Native A") || !contains(candidates, "Detour Only"))
    die("section cache native URLTest candidates should include all leaf outbounds, including hidden ones\n");
' "$core_config" "$core_config.section-cache/proxy.json" "$core_reveal_urltest_config" "$core_reveal_detour_config" || fail "native core generated URLTest behavior"

core_metadata="$WORK_DIR/core-ui-outbound-metadata.json"
ucode -L "$TACHYON_LIB" "$CACHE_UC" get-outbound-metadata "$core_config.section-cache" proxy "$WORK_DIR/missing-outbound-metadata.json" >"$core_metadata"

ucode -e '
let fs = require("fs");
let metadata = json(fs.readfile(ARGV[0]));
let names = type(metadata.names) == "object" ? metadata.names : {};
if (names["Native Group"] != null || names["proxy-urltest-out"] != null)
    die("UI outbound metadata must not include native URLTest group names\n");
if (names["Native A"] == null || names["Detour Only"] == null)
    die("UI outbound metadata should include all native leaf outbound names\n");
' "$core_metadata" || fail "native UI outbound metadata filtering"

cat >"$WORK_DIR/country-is-fixture.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "proxy",
      "selector_proxy_links": [
        "vless://00000000-0000-4000-8000-000000000001@alpha.example:443?encryption=none&security=tls&sni=alpha.example#Alpha",
        "vless://00000000-0000-4000-8000-000000000002@beta.example:443?encryption=none&security=tls&sni=beta.example#Beta"
      ]
    }
  ],
  "urltest": [
    {
      ".name": "ut_country",
      ".type": "urltest",
      "section": "proxy",
      "name": "Germany",
      "filter_mode": "include",
      "detect_server_country": "country_is",
      "include_countries": [ "DE" ]
    }
  ]
}
JSON
country_is_config="$WORK_DIR/country-is-config.json"
mkdir -p "$country_is_config.section-cache"
cat >"$country_is_config.section-cache/proxy.json" <<'JSON'
{
  "servers": {
    "proxy-1-out": "alpha.example",
    "proxy-2-out": "beta.example"
  },
  "outboundMetadata": {
    "countries": {
      "proxy-1-out": "DE",
      "proxy-2-out": "NL"
    }
  }
}
JSON
generate_config "$WORK_DIR/country-is-fixture.json" "$country_is_config"
ucode -e '
let fs = require("fs");
let config = json(fs.readfile(ARGV[0]));
let urltest = null;
for (let outbound in config.outbounds || [])
    if (outbound && outbound.tag == "proxy-urltest-ut_country-out")
        urltest = outbound;
if (!urltest || length(urltest.outbounds || []) != 1 || urltest.outbounds[0] != "proxy-1-out")
    die("cached country.is metadata was not applied to URLTest filtering\n");
' "$country_is_config" || fail "URLTest country.is cached filtering"

cat >"$WORK_DIR/xray-mixed-sub.json" <<'JSON'
[
  {
    "remarks": "Fastest Pool",
    "routing": {
      "balancers": [
        {
          "tag": "auto",
          "selector": [ "🇩🇪", "🇫🇮" ]
        }
      ]
    },
    "outbounds": [
      {
        "protocol": "vless",
        "tag": "🇩🇪 Germany-1",
        "settings": {
          "vnext": [
            {
              "address": "de1.example",
              "port": 443,
              "users": [ { "id": "00000000-0000-4000-8000-000000000011", "encryption": "none" } ]
            }
          ]
        },
        "streamSettings": { "security": "tls", "tlsSettings": { "serverName": "de1.example" } }
      },
      {
        "protocol": "vless",
        "tag": "🇫🇮 Finland-1",
        "settings": {
          "vnext": [
            {
              "address": "fi1.example",
              "port": 443,
              "users": [ { "id": "00000000-0000-4000-8000-000000000012", "encryption": "none" } ]
            }
          ]
        },
        "streamSettings": { "security": "tls", "tlsSettings": { "serverName": "fi1.example" } }
      }
    ]
  },
  {
    "remarks": "🇷🇺 Россия Премиум-1",
    "outbounds": [
      {
        "protocol": "vless",
        "tag": "proxy",
        "settings": {
          "vnext": [
            {
              "address": "ru1.example",
              "port": 443,
              "users": [ { "id": "00000000-0000-4000-8000-000000000013", "encryption": "none" } ]
            }
          ]
        },
        "streamSettings": { "security": "tls", "tlsSettings": { "serverName": "ru1.example" } }
      }
    ]
  }
]
JSON

xray_mixed_normalized="$WORK_DIR/xray-mixed-normalized.json"
normalize_subscription "$WORK_DIR/xray-mixed-sub.json" "$xray_mixed_normalized"
prepare_subscription_cache MAIN 1 "https://mixed.example/sub" "$xray_mixed_normalized"

cat >"$WORK_DIR/xray-mixed-outbound-source-fixture.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    {
      ".name": "MAIN",
      ".type": "section",
      "enabled": "1",
      "action": "connection",
      "outbound_source_refs": [ "src_sub_1" ],
      "domain_suffix": [ "example.com" ]
    }
  ],
  "outbound_source": [
    {
      ".name": "src_sub_1",
      ".type": "outbound_source",
      "enabled": "1",
      "source_type": "subscription",
      "url": "https://mixed.example/sub"
    }
  ]
}
JSON

xray_mixed_config="$WORK_DIR/xray-mixed-config.json"
generate_config "$WORK_DIR/xray-mixed-outbound-source-fixture.json" "$xray_mixed_config"
ucode -e '
let fs = require("fs");
let config = json(fs.readfile(ARGV[0]));
let selector = null;
let pool = null;
for (let ob in config.outbounds || []) {
    if (ob && ob.type == "selector" && ob.tag == "MAIN-out")
        selector = ob;
    if (ob && ob.type == "urltest" && ob.tag == "Fastest Pool")
        pool = ob;
}
if (!selector || !pool)
    die("missing MAIN-out selector or Fastest Pool urltest group when include_urltest_groups defaults to 1 on outbound_source\n");
let members = {};
for (let m in selector.outbounds || [])
    members[m] = true;
if (!members["Fastest Pool"] || !members["🇷🇺 Россия Премиум-1"] || members["🇩🇪 Germany-1"] || members["🇫🇮 Finland-1"])
    die("expected Fastest Pool group and standalone node in MAIN-out with group members hidden by default on outbound_source\n");
' "$xray_mixed_config" || fail "Xray mixed balancer + standalone subscription defaults to importing urltest groups on outbound_source"

cat >"$WORK_DIR/xray-mixed-outbound-source-off-fixture.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    {
      ".name": "MAIN",
      ".type": "section",
      "enabled": "1",
      "action": "connection",
      "outbound_source_refs": [ "src_sub_1" ],
      "domain_suffix": [ "example.com" ]
    }
  ],
  "outbound_source": [
    {
      ".name": "src_sub_1",
      ".type": "outbound_source",
      "enabled": "1",
      "source_type": "subscription",
      "url": "https://mixed.example/sub",
      "include_urltest_groups": "0"
    }
  ]
}
JSON

xray_mixed_off_config="$WORK_DIR/xray-mixed-off-config.json"
generate_config "$WORK_DIR/xray-mixed-outbound-source-off-fixture.json" "$xray_mixed_off_config"
ucode -e '
let fs = require("fs");
let config = json(fs.readfile(ARGV[0]));
let selector = null;
for (let ob in config.outbounds || [])
    if (ob && ob.type == "selector" && ob.tag == "MAIN-out")
        selector = ob;
if (!selector)
    die("missing MAIN-out selector\n");
let members = {};
for (let m in selector.outbounds || [])
    members[m] = true;
if (!members["🇩🇪 Germany-1"] || !members["🇫🇮 Finland-1"] || !members["🇷🇺 Россия Премиум-1"])
    die("expected all Xray balancer members and standalone nodes in MAIN-out when include_urltest_groups=0 on outbound_source\n");
' "$xray_mixed_off_config" || fail "Xray mixed balancer + standalone subscription preserves all servers when include_urltest_groups=0 on outbound_source"

cat >"$WORK_DIR/arblaze-sub.json" <<'JSON'
[
  {
    "remarks": "🇪🇺 Автовыбор",
    "routing": {
      "balancers": [
        {
          "tag": "balancer",
          "selector": [ "bal-1-" ]
        }
      ]
    },
    "outbounds": [
      {
        "protocol": "hysteria",
        "tag": "bal-1-hysteria",
        "settings": { "address": "nl.example", "port": 31337, "version": 2 },
        "streamSettings": {
          "network": "hysteria",
          "security": "tls",
          "tlsSettings": { "serverName": "nl.example", "alpn": [ "h3" ] },
          "hysteriaSettings": { "auth": "secret-auth", "version": 2 },
          "finalmask": {
            "udp": [
              {
                "type": "salamander",
                "settings": { "password": "gecko-pass", "packetSize": "512-1200" }
              }
            ]
          }
        }
      },
      {
        "protocol": "vless",
        "tag": "bal-1-vless",
        "settings": {
          "address": "fi.example",
          "port": 443,
          "id": "00000000-0000-4000-8000-000000000021",
          "encryption": "none"
        },
        "streamSettings": {
          "network": "xhttp",
          "security": "tls",
          "tlsSettings": { "serverName": "fi.example" },
          "xhttpSettings": { "path": "/xh", "mode": "auto" }
        }
      }
    ]
  },
  {
    "remarks": "🇳🇱 Нидерланды · Hysteria²",
    "outbounds": [
      {
        "protocol": "hysteria",
        "tag": "proxy",
        "settings": { "address": "nl.example", "port": 31337, "version": 2 },
        "streamSettings": {
          "network": "hysteria",
          "security": "tls",
          "tlsSettings": { "serverName": "nl.example", "alpn": [ "h3" ] },
          "hysteriaSettings": { "auth": "secret-auth", "version": 2 },
          "finalmask": {
            "udp": [
              {
                "type": "salamander",
                "settings": { "password": "gecko-pass", "packetSize": "512-1200" }
              }
            ]
          }
        }
      }
    ]
  },
  {
    "remarks": "🇫🇮 Финляндия · XHTTP",
    "outbounds": [
      {
        "protocol": "vless",
        "tag": "proxy",
        "settings": {
          "address": "fi.example",
          "port": 443,
          "id": "00000000-0000-4000-8000-000000000021",
          "encryption": "none"
        },
        "streamSettings": {
          "network": "xhttp",
          "security": "tls",
          "tlsSettings": { "serverName": "fi.example" },
          "xhttpSettings": { "path": "/xh", "mode": "auto" }
        }
      }
    ]
  }
]
JSON

arblaze_normalized="$WORK_DIR/arblaze-normalized.json"
normalize_subscription "$WORK_DIR/arblaze-sub.json" "$arblaze_normalized"
prepare_subscription_cache MAIN 1 "https://arblaze.example/sub" "$arblaze_normalized"

cat >"$WORK_DIR/arblaze-outbound-source-off-fixture.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    {
      ".name": "MAIN",
      ".type": "section",
      "enabled": "1",
      "action": "connection",
      "outbound_source_refs": [ "src_arblaze" ],
      "domain_suffix": [ "example.com" ]
    }
  ],
  "outbound_source": [
    {
      ".name": "src_arblaze",
      ".type": "outbound_source",
      "enabled": "1",
      "source_type": "subscription",
      "url": "https://arblaze.example/sub",
      "include_urltest_groups": "0"
    }
  ]
}
JSON

arblaze_off_config="$WORK_DIR/arblaze-off-config.json"
generate_config "$WORK_DIR/arblaze-outbound-source-off-fixture.json" "$arblaze_off_config"
ucode -e '
let fs = require("fs");
let config = json(fs.readfile(ARGV[0]));
let selector = null;
for (let ob in config.outbounds || []) {
    if (ob && ob.type == "selector" && ob.tag == "MAIN-out")
        selector = ob;
    if (ob && ob.type == "urltest" && ob.tag == "🇪🇺 Автовыбор")
        die("urltest group 🇪🇺 Автовыбор must not be emitted when include_urltest_groups=0\n");
    if (ob && (ob.tag == "bal-1-hysteria" || ob.tag == "bal-1-vless"))
        die("internal bal-1-* member must not be emitted when include_urltest_groups=0\n");
}
if (!selector)
    die("missing MAIN-out selector for arblaze (include_urltest_groups=0)\n");
let members = {};
for (let m in selector.outbounds || [])
    members[m] = true;
if (members["🇪🇺 Автовыбор"] || !members["🇳🇱 Нидерланды · Hysteria²"] || !members["🇫🇮 Финляндия · XHTTP"] || members["bal-1-hysteria"] || members["bal-1-vless"])
    die("expected only standalone servers in MAIN-out when include_urltest_groups=0\n");
' "$arblaze_off_config" || fail "ARBlazeAG subscription with include_urltest_groups=0 suppresses urltest group and bal-1-* members"

cat >"$WORK_DIR/arblaze-outbound-source-default-fixture.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    {
      ".name": "MAIN",
      ".type": "section",
      "enabled": "1",
      "action": "connection",
      "outbound_source_refs": [ "src_arblaze" ],
      "domain_suffix": [ "example.com" ]
    }
  ],
  "outbound_source": [
    {
      ".name": "src_arblaze",
      ".type": "outbound_source",
      "enabled": "1",
      "source_type": "subscription",
      "url": "https://arblaze.example/sub"
    }
  ]
}
JSON

arblaze_default_config="$WORK_DIR/arblaze-default-config.json"
generate_config "$WORK_DIR/arblaze-outbound-source-default-fixture.json" "$arblaze_default_config"
ucode -e '
let fs = require("fs");
let config = json(fs.readfile(ARGV[0]));
let selector = null;
let auto_grp = null;
for (let ob in config.outbounds || []) {
    if (ob && ob.type == "selector" && ob.tag == "MAIN-out")
        selector = ob;
    if (ob && ob.type == "urltest" && ob.tag == "🇪🇺 Автовыбор")
        auto_grp = ob;
}
if (!selector || !auto_grp)
    die("expected 🇪🇺 Автовыбор urltest group when include_urltest_groups defaults to 1 on outbound_source\n");
let members = {};
for (let m in selector.outbounds || [])
    members[m] = true;
if (!members["🇪🇺 Автовыбор"] || !members["🇳🇱 Нидерланды · Hysteria²"] || !members["🇫🇮 Финляндия · XHTTP"] || members["bal-1-hysteria"] || members["bal-1-vless"])
    die("expected 🇪🇺 Автовыбор and standalone servers in MAIN-out by default on outbound_source\n");
' "$arblaze_default_config" || fail "ARBlazeAG subscription defaults to importing urltest group on outbound_source"

cat >"$WORK_DIR/arblaze-outbound-source-fixture.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    {
      ".name": "MAIN",
      ".type": "section",
      "enabled": "1",
      "action": "connection",
      "outbound_source_refs": [ "src_arblaze" ],
      "domain_suffix": [ "example.com" ]
    }
  ],
  "outbound_source": [
    {
      ".name": "src_arblaze",
      ".type": "outbound_source",
      "enabled": "1",
      "source_type": "subscription",
      "url": "https://arblaze.example/sub",
      "include_urltest_groups": "1"
    }
  ]
}
JSON

arblaze_config="$WORK_DIR/arblaze-config.json"
generate_config "$WORK_DIR/arblaze-outbound-source-fixture.json" "$arblaze_config"
ucode -e '
let fs = require("fs");
let config = json(fs.readfile(ARGV[0]));
let cache = json(fs.readfile(ARGV[1]));
let selector = null;
let auto_grp = null;
let hy2 = null;
let bal_hy2 = false;
let bal_vless = false;
for (let ob in config.outbounds || []) {
    if (ob && ob.type == "selector" && ob.tag == "MAIN-out")
        selector = ob;
    if (ob && ob.type == "urltest" && ob.tag == "🇪🇺 Автовыбор")
        auto_grp = ob;
    if (ob && ob.type == "hysteria2" && ob.tag == "🇳🇱 Нидерланды · Hysteria²")
        hy2 = ob;
    if (ob && ob.tag == "bal-1-hysteria")
        bal_hy2 = true;
    if (ob && ob.tag == "bal-1-vless")
        bal_vless = true;
}
if (!selector)
    die("missing MAIN-out selector for arblaze\n");
if (!auto_grp || !bal_hy2 || !bal_vless)
    die("expected 🇪🇺 Автовыбор urltest group and its hidden bal-1-* backing members when include_urltest_groups=1\n");
if (!hy2 || type(hy2.obfs) != "object" || hy2.obfs.type != "gecko" || hy2.obfs.password != "gecko-pass" || hy2.obfs.min_packet_size != 512 || hy2.obfs.max_packet_size != 1200)
    die("expected Hysteria2 finalmask packetSize 512-1200 to produce gecko obfs\n");
let members = {};
for (let m in selector.outbounds || [])
    members[m] = true;
if (!members["🇪🇺 Автовыбор"] || !members["🇳🇱 Нидерланды · Hysteria²"] || !members["🇫🇮 Финляндия · XHTTP"] || members["bal-1-hysteria"] || members["bal-1-vless"])
    die("expected 🇪🇺 Автовыбор and standalone servers in MAIN-out without bal-1-* duplicates\n");
let candidates = {};
for (let c in cache.urltestCandidateTags || [])
    candidates[c] = true;
if (candidates["bal-1-hysteria"] || candidates["bal-1-vless"])
    die("internal bal-1-* members must not enter urltestCandidateTags\n");
' "$arblaze_config" "$arblaze_config.section-cache/MAIN.json" || fail "ARBlazeAG balancer + standalone subscription with include_urltest_groups=1"

cat >"$WORK_DIR/xray-country-reserve-sub.json" <<'JSON'
[
  {
    "remarks": "🇩🇪 Германия",
    "routing": {
      "balancers": [
        {
          "tag": "balancer",
          "selector": [ "proxy", "reserve-" ]
        }
      ]
    },
    "outbounds": [
      {
        "protocol": "vless",
        "tag": "proxy",
        "settings": {
          "vnext": [
            {
              "address": "de-main.example",
              "port": 443,
              "users": [ { "id": "00000000-0000-4000-8000-000000000031", "encryption": "none" } ]
            }
          ]
        },
        "streamSettings": { "security": "tls", "tlsSettings": { "serverName": "de-main.example" } }
      },
      {
        "protocol": "vless",
        "tag": "reserve-2",
        "settings": {
          "vnext": [
            {
              "address": "de-res.example",
              "port": 443,
              "users": [ { "id": "00000000-0000-4000-8000-000000000032", "encryption": "none" } ]
            }
          ]
        },
        "streamSettings": { "security": "tls", "tlsSettings": { "serverName": "de-res.example" } }
      }
    ]
  },
  {
    "remarks": "🇫🇮 Финляндия",
    "routing": {
      "balancers": [
        {
          "tag": "balancer",
          "selector": [ "proxy", "reserve-" ]
        }
      ]
    },
    "outbounds": [
      {
        "protocol": "vless",
        "tag": "proxy",
        "settings": {
          "vnext": [
            {
              "address": "fi-only-bal.example",
              "port": 443,
              "users": [ { "id": "00000000-0000-4000-8000-000000000033", "encryption": "none" } ]
            }
          ]
        },
        "streamSettings": { "security": "tls", "tlsSettings": { "serverName": "fi-only-bal.example" } }
      },
      {
        "protocol": "vless",
        "tag": "reserve-3",
        "settings": {
          "vnext": [
            {
              "address": "fi-res.example",
              "port": 443,
              "users": [ { "id": "00000000-0000-4000-8000-000000000034", "encryption": "none" } ]
            }
          ]
        },
        "streamSettings": { "security": "tls", "tlsSettings": { "serverName": "fi-res.example" } }
      }
    ]
  },
  {
    "remarks": "🇩🇪 Германия (Main)",
    "outbounds": [
      {
        "protocol": "vless",
        "tag": "proxy",
        "settings": {
          "vnext": [
            {
              "address": "de-main.example",
              "port": 443,
              "users": [ { "id": "00000000-0000-4000-8000-000000000031", "encryption": "none" } ]
            }
          ]
        },
        "streamSettings": { "security": "tls", "tlsSettings": { "serverName": "de-main.example" } }
      }
    ]
  },
  {
    "remarks": "🇺🇸 USA CH",
    "outbounds": [
      {
        "protocol": "vless",
        "tag": "proxy",
        "settings": {
          "vnext": [
            {
              "address": "us-ch.example",
              "port": 443,
              "users": [ { "id": "00000000-0000-4000-8000-000000000035", "encryption": "none" } ]
            }
          ]
        },
        "streamSettings": { "security": "tls", "tlsSettings": { "serverName": "us-ch.example" } }
      }
    ]
  }
]
JSON

country_res_normalized="$WORK_DIR/xray-country-reserve-normalized.json"
normalize_subscription "$WORK_DIR/xray-country-reserve-sub.json" "$country_res_normalized"
prepare_subscription_cache MAIN 1 "https://country-res.example/sub" "$country_res_normalized"

cat >"$WORK_DIR/country-res-off-fixture.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    {
      ".name": "MAIN",
      ".type": "section",
      "enabled": "1",
      "action": "connection",
      "outbound_source_refs": [ "src_country" ],
      "domain_suffix": [ "example.com" ]
    }
  ],
  "outbound_source": [
    {
      ".name": "src_country",
      ".type": "outbound_source",
      "enabled": "1",
      "source_type": "subscription",
      "url": "https://country-res.example/sub",
      "include_urltest_groups": "0"
    }
  ]
}
JSON

country_off_config="$WORK_DIR/country-res-off-config.json"
generate_config "$WORK_DIR/country-res-off-fixture.json" "$country_off_config"
ucode -e '
let fs = require("fs");
let config = json(fs.readfile(ARGV[0]));
let cache = json(fs.readfile(ARGV[1]));
let selector = null;
let servers = {};
for (let ob in config.outbounds || []) {
    if (!ob) continue;
    if (ob.type == "selector" && ob.tag == "MAIN-out")
        selector = ob;
    if (ob.type == "urltest")
        die("unexpected subscription urltest group in config when include_urltest_groups=0: " + ob.tag + "\n");
    if (index(lc(ob.tag || ""), "reserve") >= 0)
        die("reserve node leaked into config when include_urltest_groups=0: " + ob.tag + "\n");
    if (ob.server)
        servers[ob.server] = ob.tag;
}
if (!selector)
    die("missing MAIN-out selector for country-reserve disabled test\n");
let members = {};
for (let m in selector.outbounds || [])
    members[m] = true;
if (!members["🇺🇸 USA CH"] || !members["🇩🇪 Германия (Main)"])
    die("missing primary servers in MAIN-out\n");
if (!servers["fi-only-bal.example"] || !members[servers["fi-only-bal.example"]])
    die("primary server from balancer-only country must survive in MAIN-out\n");
if (servers["fi-only-bal.example"] != "🇫🇮 Финляндия")
    die("expected primary server from balancer-only country to inherit group label 🇫🇮 Финляндия, got: " + servers["fi-only-bal.example"] + "\n");
let candidates = {};
for (let c in cache.urltestCandidateTags || [])
    candidates[c] = true;
if (!candidates["🇺🇸 USA CH"] || !candidates["🇩🇪 Германия (Main)"] || !candidates[servers["fi-only-bal.example"]])
    die("expected real servers in Fastest urltestCandidateTags\n");
' "$country_off_config" "$country_off_config.section-cache/MAIN.json" || fail "Xray country balancers with reserve-* nodes drop urltest groups and reserve-* when include_urltest_groups=0"

cat >"$WORK_DIR/country-res-on-fixture.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    {
      ".name": "MAIN",
      ".type": "section",
      "enabled": "1",
      "action": "connection",
      "outbound_source_refs": [ "src_country" ],
      "domain_suffix": [ "example.com" ]
    }
  ],
  "outbound_source": [
    {
      ".name": "src_country",
      ".type": "outbound_source",
      "enabled": "1",
      "source_type": "subscription",
      "url": "https://country-res.example/sub",
      "include_urltest_groups": "1"
    }
  ]
}
JSON

country_on_config="$WORK_DIR/country-res-on-config.json"
generate_config "$WORK_DIR/country-res-on-fixture.json" "$country_on_config"
ucode -e '
let fs = require("fs");
let config = json(fs.readfile(ARGV[0]));
let cache = json(fs.readfile(ARGV[1]));
let selector = null;
let has_de_grp = false;
let has_fi_grp = false;
for (let ob in config.outbounds || []) {
    if (!ob) continue;
    if (ob.type == "selector" && ob.tag == "MAIN-out")
        selector = ob;
    if (ob.type == "urltest" && ob.tag == "🇩🇪 Германия")
        has_de_grp = true;
    if (ob.type == "urltest" && ob.tag == "🇫🇮 Финляндия")
        has_fi_grp = true;
}
if (!selector || !has_de_grp || !has_fi_grp)
    die("expected country urltest groups when include_urltest_groups=1\n");
let members = {};
for (let m in selector.outbounds || [])
    members[m] = true;
if (!members["🇩🇪 Германия"] || !members["🇫🇮 Финляндия"] || !members["🇺🇸 USA CH"])
    die("expected country urltest groups and standalone node in MAIN-out when include_urltest_groups=1\n");
for (let m in selector.outbounds || [])
    if (index(lc(m), "reserve") >= 0)
        die("reserve node must stay hidden inside urltest group, got in selector: " + m + "\n");
for (let c in cache.urltestCandidateTags || [])
    if (index(lc(c), "reserve") >= 0)
        die("reserve node must not enter urltestCandidateTags: " + c + "\n");
' "$country_on_config" "$country_on_config.section-cache/MAIN.json" || fail "Xray country balancers with include_urltest_groups=1 keep reserve-* hidden inside groups"

printf 'URLTest group checks passed\n'
