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

GENERATOR_UC="$TACHYON_LIB/tachyon_core/generator.uc"
VALIDATOR_UC="$TACHYON_LIB/config/validator.uc"

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

validate_fixture() {
  local fixture="$1"
  TACHYON_LIB="$TACHYON_LIB" ucode -L "$TACHYON_LIB" "$VALIDATOR_UC" \
    validate-runtime-fixture "$fixture" "{}"
}

cat >"$WORK_DIR/mixed.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "dns_server": [ "77.88.8.8" ],
    "bootstrap_dns_server": [ "77.88.8.8" ]
  },
  "section": [
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "connection",
      "outbound_jsons": [
        "{\"type\":\"vless\",\"tag\":\"Alpha\",\"server\":\"alpha.example\",\"server_port\":443,\"uuid\":\"00000000-0000-4000-8000-000000000001\",\"tls\":{\"enabled\":true}}",
        "{\"type\":\"vless\",\"tag\":\"Beta\",\"server\":\"beta.example\",\"server_port\":443,\"uuid\":\"00000000-0000-4000-8000-000000000002\",\"transport\":{\"type\":\"ws\"},\"tls\":{\"enabled\":true,\"reality\":{\"enabled\":true}}}",
        "{\"type\":\"vmess\",\"tag\":\"Gamma\",\"server\":\"gamma.example\",\"server_port\":443,\"uuid\":\"00000000-0000-4000-8000-000000000003\",\"transport\":{\"type\":\"grpc\"}}",
        "{\"type\":\"trojan\",\"tag\":\"Delta\",\"server\":\"delta.example\",\"server_port\":443,\"password\":\"secret\",\"transport\":{\"type\":\"xhttp\"},\"tls\":{\"enabled\":true}}",
        "{\"type\":\"http\",\"tag\":\"Echo\",\"server\":\"echo.example\",\"server_port\":8080}"
      ],
      "dashboard_filter_mode": "mixed",
      "dashboard_include_proxy_parameters": "1",
      "dashboard_include_protocols": [ "http" ],
      "dashboard_include_groups": [ "Shared group" ],
      "dashboard_exclude_groups": [ "Blocked group" ]
    }
  ],
  "urltest": [
    {
      ".name": "ut_main",
      ".type": "urltest",
      "section": "proxy",
      "name": "Shared group",
      "filter_mode": "include",
      "include_outbounds": [ "Alpha", "Beta" ]
    }
  ],
  "priority_group": [
    {
      ".name": "pg_shared",
      ".type": "priority_group",
      "section": "proxy",
      "name": "Shared group"
    },
    {
      ".name": "pg_main",
      ".type": "priority_group",
      "section": "proxy",
      "name": "Blocked group"
    }
  ],
  "priority_level": [
    {
      ".name": "pl_shared",
      ".type": "priority_level",
      "group": "pg_shared",
      "name": "Shared members",
      "order": "0",
      "filter_mode": "include",
      "include_outbounds": [ "Gamma" ]
    },
    {
      ".name": "pl_main",
      ".type": "priority_level",
      "group": "pg_main",
      "name": "Blocked members",
      "order": "0",
      "filter_mode": "include",
      "include_outbounds": [ "Beta", "Gamma" ]
    }
  ]
}
JSON

node - "$WORK_DIR/mixed.json" "$WORK_DIR" <<'JS'
const fs = require('fs');
const path = require('path');
const source = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
const outputDir = process.argv[3];

for (const mode of ['disabled', 'include', 'exclude']) {
  const fixture = JSON.parse(JSON.stringify(source));
  const section = fixture.section[0];
  section.dashboard_filter_mode = mode;
  if (mode === 'disabled') {
    delete section.dashboard_include_proxy_parameters;
    delete section.dashboard_include_protocols;
    delete section.dashboard_include_groups;
    delete section.dashboard_exclude_groups;
  } else if (mode === 'include') {
    delete section.dashboard_include_proxy_parameters;
    delete section.dashboard_include_protocols;
    delete section.dashboard_exclude_groups;
  } else {
    delete section.dashboard_include_proxy_parameters;
    delete section.dashboard_include_protocols;
    delete section.dashboard_include_groups;
  }
  fs.writeFileSync(path.join(outputDir, `${mode}.json`), JSON.stringify(fixture));
}

const invalid = JSON.parse(JSON.stringify(source));
invalid.section[0].dashboard_include_groups = ['missing_group'];
fs.writeFileSync(path.join(outputDir, 'invalid-group.json'), JSON.stringify(invalid));

const invalidMode = JSON.parse(JSON.stringify(source));
invalidMode.section[0].dashboard_filter_mode = 'unknown';
fs.writeFileSync(path.join(outputDir, 'invalid-mode.json'), JSON.stringify(invalidMode));

const invalidPort = JSON.parse(JSON.stringify(source));
invalidPort.section[0].dashboard_include_ports = ['70000'];
fs.writeFileSync(path.join(outputDir, 'invalid-port.json'), JSON.stringify(invalidPort));
JS

for mode in disabled include exclude mixed; do
  validate_fixture "$WORK_DIR/$mode.json" >/dev/null || fail "$mode dashboard filter validation"
  generate_config "$WORK_DIR/$mode.json" "$WORK_DIR/$mode-config.json"
done

if validate_fixture "$WORK_DIR/invalid-group.json" >/dev/null 2>&1; then
  fail "unknown dashboard group should be rejected"
fi

if validate_fixture "$WORK_DIR/invalid-mode.json" >/dev/null 2>&1; then
  fail "unknown dashboard filter mode should be rejected"
fi

if validate_fixture "$WORK_DIR/invalid-port.json" >/dev/null 2>&1; then
  fail "invalid dashboard port should be rejected"
fi

ucode -e '
let fs = require("fs");
function fail(message) { die(message + "\n"); }
function outbound_by_tag(config, tag) {
    for (let outbound in config.outbounds || [])
        if (outbound && outbound.tag == tag)
            return outbound;
    return null;
}
function assert_array(value, expected, label) {
    value = value || [];
    if (length(value) != length(expected))
        fail(label + " length mismatch: " + sprintf("%J", value));
    for (let i = 0; i < length(expected); i++)
        if (value[i] != expected[i])
            fail(label + " mismatch: " + sprintf("%J", value));
}
let disabled = outbound_by_tag(json(fs.readfile(ARGV[0])), "proxy-out");
let include = outbound_by_tag(json(fs.readfile(ARGV[1])), "proxy-out");
let exclude = outbound_by_tag(json(fs.readfile(ARGV[2])), "proxy-out");
let mixed = outbound_by_tag(json(fs.readfile(ARGV[3])), "proxy-out");
assert_array(disabled.outbounds, [ "Alpha", "Beta", "Gamma", "Delta", "Echo", "proxy-urltest-ut_main-out", "proxy-priority-pg_shared-out", "proxy-priority-pg_main-out" ], "all dashboard servers");
assert_array(include.outbounds, [ "Alpha", "Beta", "Gamma", "proxy-urltest-ut_main-out", "proxy-priority-pg_shared-out", "proxy-priority-pg_main-out" ], "same-name URLTest and Priority groups");
assert_array(exclude.outbounds, [ "Alpha", "Delta", "Echo", "proxy-urltest-ut_main-out", "proxy-priority-pg_shared-out", "proxy-priority-pg_main-out" ], "excluded Priority group");
assert_array(mixed.outbounds, [ "Alpha", "Echo", "proxy-urltest-ut_main-out", "proxy-priority-pg_shared-out", "proxy-priority-pg_main-out" ], "mixed group and proxy filters");
if (mixed.default != "proxy-urltest-ut_main-out")
    fail("section selector should still default to the first URLTest group");
' "$WORK_DIR/disabled-config.json" "$WORK_DIR/include-config.json" \
  "$WORK_DIR/exclude-config.json" "$WORK_DIR/mixed-config.json" ||
  fail "dashboard server filter regression"

# ─── Issue #89: Section server exclusion cascades to URLTest & Priority groups ─
cat >"$WORK_DIR/issue89.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "dns_server": [ "77.88.8.8" ],
    "bootstrap_dns_server": [ "77.88.8.8" ]
  },
  "section": [
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "connection",
      "outbound_jsons": [
        "{\"type\":\"vless\",\"tag\":\"🇳🇱 Amsterdam\",\"server\":\"nl.example\",\"server_port\":443,\"uuid\":\"00000000-0000-4000-8000-000000000001\"}",
        "{\"type\":\"vless\",\"tag\":\"🇷🇺 Moscow\",\"server\":\"ru.example\",\"server_port\":443,\"uuid\":\"00000000-0000-4000-8000-000000000002\"}",
        "{\"type\":\"vless\",\"tag\":\"🇩🇪 Berlin\",\"server\":\"de.example\",\"server_port\":443,\"uuid\":\"00000000-0000-4000-8000-000000000003\"}"
      ],
      "dashboard_filter_mode": "exclude",
      "dashboard_detect_server_country": "flag_emoji",
      "dashboard_exclude_countries": [ "RU" ]
    }
  ],
  "urltest": [
    {
      ".name": "ut_auto",
      ".type": "urltest",
      "section": "proxy",
      "name": "Auto Main",
      "filter_mode": "disabled"
    }
  ],
  "priority_group": [
    {
      ".name": "pg_auto",
      ".type": "priority_group",
      "section": "proxy",
      "name": "Priority Main"
    }
  ],
  "priority_level": [
    {
      ".name": "pl_auto",
      ".type": "priority_level",
      "group": "pg_auto",
      "name": "Level 1",
      "order": "0",
      "filter_mode": "disabled"
    }
  ]
}
JSON

validate_fixture "$WORK_DIR/issue89.json" >/dev/null || fail "issue89 fixture validation"
generate_config "$WORK_DIR/issue89.json" "$WORK_DIR/issue89-config.json"

ucode -e '
let fs = require("fs");
function fail(message) { die(message + "\n"); }
function outbound_by_tag(config, tag) {
    for (let outbound in config.outbounds || [])
        if (outbound && outbound.tag == tag)
            return outbound;
    return null;
}
function assert_array(value, expected, label) {
    value = value || [];
    if (length(value) != length(expected))
        fail(label + " length mismatch: " + sprintf("%J", value));
    for (let i = 0; i < length(expected); i++)
        if (value[i] != expected[i])
            fail(label + " mismatch: " + sprintf("%J", value));
}
let cfg = json(fs.readfile(ARGV[0]));
let selector = outbound_by_tag(cfg, "proxy-out");
let urltest = outbound_by_tag(cfg, "proxy-urltest-ut_auto-out");
let priority = outbound_by_tag(cfg, "proxy-priority-pg_auto-out");

if (!selector) fail("missing proxy-out selector");
if (!urltest) fail("missing proxy-urltest-ut_auto-out outbound");
if (!priority) fail("missing proxy-priority-pg_auto-out outbound");

assert_array(urltest.outbounds, [ "🇳🇱 Amsterdam", "🇩🇪 Berlin" ], "URLTest outbounds must not include section-excluded RU server");
assert_array(priority.outbounds, [ "🇳🇱 Amsterdam", "🇩🇪 Berlin" ], "Priority outbounds must not include section-excluded RU server");
assert_array(selector.outbounds, [ "🇳🇱 Amsterdam", "🇩🇪 Berlin", "proxy-urltest-ut_auto-out", "proxy-priority-pg_auto-out" ], "Selector outbounds must not include section-excluded RU server");

if (selector.default != "proxy-urltest-ut_auto-out")
    fail("selector default must be the urltest group");
' "$WORK_DIR/issue89-config.json" || fail "issue89 cascade exclusion regression"

mkdir -p "$WORK_DIR/sub_test/subscriptions"
cat >"$WORK_DIR/sub_test/subscriptions/proxy-subscription-1.json" <<'JSON'
{
  "outbounds": [
    { "type": "vless", "tag": "dk1", "remark": "🇩🇰 Denmark ⚡", "server": "127.0.0.1", "server_port": 1101, "uuid": "00000000-0000-4000-8000-000000000001", "transport": { "type": "tcp" } },
    { "type": "vless", "tag": "dk2", "remark": "🇩🇰 Denmark ⚡", "server": "127.0.0.1", "server_port": 1102, "uuid": "00000000-0000-4000-8000-000000000002", "transport": { "type": "xhttp" } },
    { "type": "vless", "tag": "dk3", "remark": "🇩🇰 Denmark ⚡", "server": "127.0.0.1", "server_port": 1103, "uuid": "00000000-0000-4000-8000-000000000003", "transport": { "type": "tcp" } }
  ]
}
JSON
printf '%s\n' 'https://dup.example/sub' >"$WORK_DIR/sub_test/subscriptions/proxy-subscription-1.url"
: >"$WORK_DIR/sub_test/subscriptions/proxy-subscription-1.user_agent"

cat >"$WORK_DIR/duplicate-names.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings"
  },
  "section": [
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "connection",
      "subscription_urls": [ "https://dup.example/sub" ]
    }
  ],
  "urltest": [
    {
      ".name": "ut_xhttp_only",
      ".type": "urltest",
      "section": "proxy",
      "name": "XHTTP only",
      "filter_mode": "include",
      "include_outbounds": [ "🇩🇰 Denmark ⚡ [VLESS (XHTTP)]" ]
    },
    {
      ".name": "ut_tcp_only",
      ".type": "urltest",
      "section": "proxy",
      "name": "TCP only",
      "filter_mode": "include",
      "include_outbounds": [ "🇩🇰 Denmark ⚡ [VLESS (TCP)]" ]
    },
    {
      ".name": "ut_tcp_second",
      ".type": "urltest",
      "section": "proxy",
      "name": "TCP #2 only",
      "filter_mode": "include",
      "include_outbounds": [ "🇩🇰 Denmark ⚡ [VLESS (TCP)] (#2)" ]
    },
    {
      ".name": "ut_both_name",
      ".type": "urltest",
      "section": "proxy",
      "name": "Both by plain name",
      "filter_mode": "include",
      "include_outbounds": [ "🇩🇰 Denmark ⚡" ]
    }
  ]
}
JSON

TMP_SUBSCRIPTION_FOLDER="$WORK_DIR/sub_test/subscriptions" \
  generate_config "$WORK_DIR/duplicate-names.json" "$WORK_DIR/duplicate-names-config.json"

ucode -e '
let fs = require("fs");
function fail(msg) { die(msg + "\n"); }
function outbound_by_tag(cfg, tag) {
    for (let o in cfg.outbounds || [])
        if (o && o.tag == tag) return o;
    return null;
}
function assert_array(val, exp, label) {
    val = val || [];
    if (length(val) != length(exp)) fail(label + " len mismatch: " + sprintf("%J", val) + " vs " + sprintf("%J", exp));
    for (let i = 0; i < length(exp); i++)
        if (val[i] != exp[i]) fail(label + " mismatch: " + sprintf("%J", val));
}
let cfg = json(fs.readfile(ARGV[0]));
let ut_xhttp = outbound_by_tag(cfg, "proxy-urltest-ut_xhttp_only-out");
let ut_tcp = outbound_by_tag(cfg, "proxy-urltest-ut_tcp_only-out");
let ut_tcp2 = outbound_by_tag(cfg, "proxy-urltest-ut_tcp_second-out");
let ut_both = outbound_by_tag(cfg, "proxy-urltest-ut_both_name-out");

if (!ut_xhttp) fail("missing ut_xhttp");
if (!ut_tcp) fail("missing ut_tcp");
if (!ut_tcp2) fail("missing ut_tcp2");
if (!ut_both) fail("missing ut_both");

assert_array(ut_xhttp.outbounds, [ "dk2" ], "XHTTP only must select only the XHTTP node");
assert_array(ut_tcp.outbounds, [ "dk1" ], "TCP only must select only the TCP node");
assert_array(ut_tcp2.outbounds, [ "dk3" ], "TCP #2 only must select only the second TCP node");
assert_array(ut_both.outbounds, [ "dk1", "dk2", "dk3" ], "Plain name must select all three nodes");
' "$WORK_DIR/duplicate-names-config.json" || fail "duplicate outbound name disambiguation failed"

# ─── TCH-1020: Subscription nodes in URLTest groups selected via dashboard filter ───
mkdir -p "$WORK_DIR/tch1020/subscriptions"
cat >"$WORK_DIR/tch1020/subscriptions/proxy-subscription-1.json" <<'JSON'
{
  "outbounds": [
    { "type": "urltest", "tag": "PomidorVPN - Group", "remark": "PomidorVPN - Group", "outbounds": [ "us1", "us2", "de1" ], "__tachyon_allow_group": true },
    { "type": "vless", "tag": "us1", "remark": "🇺🇸США", "server": "1.1.1.1", "server_port": 443, "uuid": "00000000-0000-4000-8000-000000000001" },
    { "type": "vless", "tag": "us2", "remark": "🇺🇸США 2", "server": "1.1.1.2", "server_port": 443, "uuid": "00000000-0000-4000-8000-000000000002" },
    { "type": "vless", "tag": "de1", "remark": "🇩🇪Германия", "server": "1.1.1.3", "server_port": 443, "uuid": "00000000-0000-4000-8000-000000000003" }
  ]
}
JSON
printf '%s\n' 'https://pomidor.example/sub' >"$WORK_DIR/tch1020/subscriptions/proxy-subscription-1.url"
: >"$WORK_DIR/tch1020/subscriptions/proxy-subscription-1.user_agent"

cat >"$WORK_DIR/tch1020-include.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "dns_server": [ "77.88.8.8" ]
  },
  "section": [
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "connection",
      "subscription_urls": [ "https://pomidor.example/sub" ],
      "selector_proxy_links": [ "http://1.2.3.4:8080#OperaUS-1-out" ],
      "dashboard_filter_mode": "include",
      "dashboard_include_outbounds": [ "🇺🇸США", "🇺🇸США 2", "OperaUS-1-out [HTTP (TCP)]" ]
    }
  ]
}
JSON

TMP_SUBSCRIPTION_FOLDER="$WORK_DIR/tch1020/subscriptions" \
  generate_config "$WORK_DIR/tch1020-include.json" "$WORK_DIR/tch1020-include-config.json"

ucode -e '
let fs = require("fs");
function fail(msg) { die(msg + "\n"); }
function outbound_by_tag(cfg, tag) {
    for (let o in cfg.outbounds || [])
        if (o && o.tag == tag) return o;
    return null;
}
function assert_array(val, exp, label) {
    val = val || [];
    if (length(val) != length(exp)) fail(label + " len mismatch: " + sprintf("%J", val) + " vs " + sprintf("%J", exp));
    for (let i = 0; i < length(exp); i++)
        if (val[i] != exp[i]) fail(label + " mismatch: " + sprintf("%J", val));
}
let cfg = json(fs.readfile(ARGV[0]));
let sel = outbound_by_tag(cfg, "proxy-out");
if (!sel) fail("missing proxy-out selector");
assert_array(sel.outbounds, [ "proxy-1-out", "us1", "us2" ], "TCH-1020: selector must include selected subscription nodes and manual http link");

let cache = json(fs.readfile(ARGV[1]));
if (!cache) fail("missing section cache");
if (cache.hiddenOutboundTags["us1"]) fail("us1 must not be marked hidden in section cache");
if (cache.hiddenOutboundTags["us2"]) fail("us2 must not be marked hidden in section cache");
if (cache.hiddenOutboundTags["proxy-1-out"]) fail("proxy-1-out must not be marked hidden in section cache");
if (!cache.hiddenOutboundTags["de1"]) fail("unselected subscription node de1 must remain marked hidden in section cache");
' "$WORK_DIR/tch1020-include-config.json" "$WORK_DIR/tch1020-include-config.json.section-cache/proxy.json" || fail "TCH-1020 regression check failed"

# ─── Include filter that matches nothing must not collapse the section ───
# A stale/renamed entry (e.g. after a node prefix change) used to leave the
# selector holding only the URLTest group: the section silently lost every
# server. It now falls back to all loaded servers (TCH-1036 follow-up).
sed -e 's/"dashboard_include_outbounds": \[ .* \]/"dashboard_include_outbounds": [ "server-that-no-longer-exists" ]/' \
    "$WORK_DIR/tch1020-include.json" >"$WORK_DIR/stale-filter.json"

TMP_SUBSCRIPTION_FOLDER="$WORK_DIR/tch1020/subscriptions" \
  generate_config "$WORK_DIR/stale-filter.json" "$WORK_DIR/stale-filter-config.json"

ucode -e '
let fs = require("fs");
function fail(msg) { die(msg + "\n"); }
function outbound_by_tag(cfg, tag) {
    for (let o in cfg.outbounds || [])
        if (o && o.tag == tag) return o;
    return null;
}
let cfg = json(fs.readfile(ARGV[0]));
let sel = outbound_by_tag(cfg, "proxy-out");
if (!sel) fail("missing proxy-out selector");
let members = sel.outbounds || [];
// The group alone means the section collapsed; the manual link proves the
// fallback restored every loaded server.
if (length(members) < 2)
    fail("stale include filter must fall back to all loaded servers, got: " + sprintf("%J", members));
let has_manual = false;
for (let m in members)
    if (m == "proxy-1-out") has_manual = true;
if (!has_manual)
    fail("fallback must keep the manual proxy link, got: " + sprintf("%J", members));
' "$WORK_DIR/stale-filter-config.json" || fail "stale include filter regression"

printf 'dashboard server filter checks passed\n'
