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

VALIDATOR="$TACHYON_LIB/config/validator.uc"

# validator warnings go through logger(1); stub it so assertions can read them
LOGGER_LOG="$WORK_DIR/logger.log"
mkdir -p "$WORK_DIR/bin"
cat >"$WORK_DIR/bin/logger" <<BASH
#!/usr/bin/env bash
printf '%s\n' "\$*" >> "$LOGGER_LOG"
BASH
chmod +x "$WORK_DIR/bin/logger"

cat >"$WORK_DIR/context.json" <<'JSON'
{}
JSON

context="$(cat "$WORK_DIR/context.json")"

validate_fixture() {
  local source="$1"
  local normalized="$WORK_DIR/normalized-$(basename "$source")"
  node - "$source" "$normalized" <<'JS'
const fs = require('fs');
const input = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
if (input.settings === undefined || input.settings === null) input.settings = { '.name': 'settings', '.type': 'settings' };
if (input.settings.dns_server === undefined) input.settings.dns_server = ['77.88.8.8'];
if (input.settings.bootstrap_dns_server === undefined) input.settings.bootstrap_dns_server = ['77.88.8.8'];
fs.writeFileSync(process.argv[3], JSON.stringify(input));
JS
  TACHYON_LIB="$TACHYON_LIB" PATH="$WORK_DIR/bin:$PATH" ucode -L "$TACHYON_LIB" "$VALIDATOR" validate-runtime-fixture "$normalized" "$context"
}

# Warnings never reach stdout, so read them back from the logger stub.
assert_warns() {
  local label="$1"
  local fixture="$2"
  local expected="$3"
  local output

  : >"$LOGGER_LOG"
  if ! output="$(validate_fixture "$fixture" 2>/dev/null)"; then
    fail "$label should be accepted, got '$output'"
  fi

  grep -Fq "$expected" "$LOGGER_LOG" ||
    fail "$label: expected a warning containing '$expected', got '$(cat "$LOGGER_LOG")'"
}

assert_no_warning() {
  local label="$1"
  local fixture="$2"
  local unexpected="$3"
  local output

  : >"$LOGGER_LOG"
  if ! output="$(validate_fixture "$fixture" 2>/dev/null)"; then
    fail "$label should be accepted, got '$output'"
  fi

  if grep -Fq "$unexpected" "$LOGGER_LOG"; then
    fail "$label: unexpected warning containing '$unexpected'"
  fi
}

assert_rejects() {
  local label="$1"
  local fixture="$2"
  local expected="$3"
  local output

  if output="$(validate_fixture "$fixture" 2>/dev/null)"; then
    fail "$label should be rejected"
  fi

  printf '%s\n' "$output" | grep -Fq "$expected" ||
    fail "$label: expected message containing '$expected', got '$output'"
}

cat >"$WORK_DIR/valid.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "list_update_enabled": "1",
    "update_interval": "1d",
    "latency_test_url": "https://latency.example/generate_204",
    "dns_type": "doh",
    "dns_server": [ "dns.google/dns-query", "cloudflare-dns.com/dns-query" ],
    "bootstrap_dns_server": [ "1.1.1.1", "8.8.8.8" ],
    "dns_check_interval": "10s",
    "dns_recovery_check_interval": "60s",
    "dns_check_timeout": "2s",
    "dns_strategy": "prefer_ipv6",
    "dns_detour_enabled": "1",
    "dns_detour_section": "proxy",
    "download_lists_via_proxy": "1",
    "download_lists_via_proxy_section": "proxy"
  },
  "section": [
    {
      ".name": "detour",
      ".type": "section",
      "enabled": "1",
      "action": "outbound",
      "outbound_json": "{\"type\":\"direct\"}",
      "domain_suffix": [ "detour.example" ]
    },
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "proxy",
      "ports": [ "80", "1000-2000" ],
      "subscription_urls": [ "https://example.com/sub.txt" ],
      "subscription_url_settings": "{\"https://example.com/sub.txt\":{\"user_agent\":\"Agent/1.0\"}}",
      "subscription_update_enabled": "1",
      "subscription_update_interval": "12h",
      "urltest_enabled": "1",
      "urltest_check_interval": "3m",
      "urltest_filter_mode": "mixed",
      "urltest_tolerance": "10000",
      "urltest_testing_url": "https://urltest.example/generate_204",
      "urltest_include_countries": [ "US" ],
      "urltest_exclude_regex": [ "bad.*" ],
      "detect_server_country": "flag_emoji",
      "domain": "commented.example # keep this note\nfull:exact-comment.example // and this note\nkeyword:clip",
      "domain_suffix": [ "example.org", "сайт.рф", "full:exact.example", "full:full:legacy.example", "full:пример.испытание", "keyword:video", "keyword:пример", "regex:^api[.]example$", "regex:^сайт[.]рф$" ],
      "domain_suffix_text": "text.example\nmünich.example\nkeyword:stream",
      "community_lists": [ "discord" ],
      "rule_set": [ "https://example.com/rules.srs" ],
      "rule_set_with_subnets": [ "/tmp/local.json" ],
      "domain_ip_lists": [ "https://example.com/mixed.lst", "/etc/tachyon/list.txt" ],
      "outbound_detour_enabled": "1",
      "outbound_detour_section": "detour"
    },
    {
      ".name": "bypass",
      ".type": "section",
      "enabled": "1",
      "action": "bypass",
      "domain_suffix": [ "bypass.example" ]
    },
    {
      ".name": "des",
      ".type": "section",
      "enabled": "1",
      "action": "desync",
      "desync_preset": "auto",
      "domain_ip_lists": [ "https://example.com/provider.lst" ]
    },
    {
      ".name": "custom_dns",
      ".type": "section",
      "enabled": "1",
      "action": "dns",
      "dns_type": "dot",
      "dns_server": "9.9.9.9:5353",
      "dns_detour_enabled": "1",
      "dns_detour_section": "proxy",
      "domain_suffix": [ "dns.example" ],
      "rule_set": [ "https://example.com/domain-only.srs" ],
      "domain_ip_lists": [ "https://example.com/domains.lst" ]
    }
  ],
  "server": [
    {
      ".name": "srv",
      ".type": "server",
      "enabled": "1",
      "routing_mode": "section",
      "routing_section": "proxy"
    }
  ]
}
JSON

validate_fixture "$WORK_DIR/valid.json"

cat >"$WORK_DIR/bad-dns-duration.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "dns_server": [ "1.1.1.1", "8.8.8.8" ],
    "bootstrap_dns_server": [ "77.88.8.8" ],
    "dns_check_interval": "ten seconds"
  },
  "section": []
}
JSON
assert_rejects "bad DNS interval" "$WORK_DIR/bad-dns-duration.json" "settings.dns_check_interval"

cat >"$WORK_DIR/bad-dns-server.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "dns_server": [ "1.1.1.1", "bad value" ],
    "bootstrap_dns_server": [ "77.88.8.8" ]
  },
  "section": []
}
JSON
assert_rejects "bad DNS server" "$WORK_DIR/bad-dns-server.json" "Invalid main DNS server"

cat >"$WORK_DIR/bad-dns-strategy.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "dns_strategy": "auto"
  },
  "section": []
}
JSON
assert_rejects "bad DNS strategy" "$WORK_DIR/bad-dns-strategy.json" "Unsupported DNS strategy 'auto'"

cat >"$WORK_DIR/empty-main-dns.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "dns_server": [],
    "bootstrap_dns_server": [ "77.88.8.8" ]
  },
  "section": []
}
JSON
assert_rejects "empty main DNS list" "$WORK_DIR/empty-main-dns.json" "At least one main DNS server is required"

cat >"$WORK_DIR/empty-bootstrap-dns.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "dns_server": [ "77.88.8.8" ],
    "bootstrap_dns_server": []
  },
  "section": []
}
JSON
assert_rejects "empty Bootstrap DNS list" "$WORK_DIR/empty-bootstrap-dns.json" "At least one Bootstrap DNS server is required"

cat >"$WORK_DIR/bad-dns-detour-bypass.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "dns_detour_enabled": "1",
    "dns_detour_section": "bypass"
  },
  "section": [
    { ".name": "bypass", ".type": "section", "enabled": "1", "action": "bypass" }
  ]
}
JSON
assert_rejects "DNS detour bypass" "$WORK_DIR/bad-dns-detour-bypass.json" "unsupported action 'bypass'"

cat >"$WORK_DIR/bad-direct-action.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "old", ".type": "section", "enabled": "1", "action": "direct" }
  ]
}
JSON
assert_rejects "bad direct action" "$WORK_DIR/bad-direct-action.json" "unsupported action 'direct'"

cat >"$WORK_DIR/bad-dns-rule-server.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "dns", ".type": "section", "enabled": "1", "action": "dns", "dns_server": "bad value", "domain_suffix": [ "example.org" ] }
  ]
}
JSON
assert_rejects "bad DNS rule server" "$WORK_DIR/bad-dns-rule-server.json" "invalid DNS server"

cat >"$WORK_DIR/bad-dns-rule-protocol.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "dns", ".type": "section", "enabled": "1", "action": "dns", "dns_type": "tcp", "dns_server": "9.9.9.9", "domain_suffix": [ "example.org" ] }
  ]
}
JSON
assert_rejects "bad DNS rule protocol" "$WORK_DIR/bad-dns-rule-protocol.json" "unsupported protocol 'tcp'"

cat >"$WORK_DIR/url-in-fallback-dns.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "dns_server": [ "1.1.1.1" ],
    "bootstrap_dns_server": [ "77.88.8.8" ],
    "dns_fallback_server": [ "https://cloudflare-dns.com/dns-query" ]
  },
  "section": []
}
JSON
assert_rejects "URL in dns_fallback_server" "$WORK_DIR/url-in-fallback-dns.json" "Fallback DNS server"

cat >"$WORK_DIR/path-doh-in-fallback-dns.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "dns_server": [ "1.1.1.1" ],
    "bootstrap_dns_server": [ "77.88.8.8" ],
    "dns_fallback_server": [ "cloudflare-dns.com/dns-query" ]
  },
  "section": []
}
JSON
assert_rejects "path-style DoH in dns_fallback_server" "$WORK_DIR/path-doh-in-fallback-dns.json" "Fallback DNS server"

cat >"$WORK_DIR/bad-dns-rule-matchers.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "dns", ".type": "section", "enabled": "1", "action": "dns", "dns_server": "9.9.9.9" }
  ]
}
JSON
assert_rejects "DNS rule without domain matchers" "$WORK_DIR/bad-dns-rule-matchers.json" "must contain at least one domain condition"

cat >"$WORK_DIR/bad-dns-rule-subnets.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "dns", ".type": "section", "enabled": "1", "action": "dns", "dns_server": "9.9.9.9", "rule_set_with_subnets": [ "https://example.com/mixed.srs" ] }
  ]
}
JSON
assert_rejects "DNS rule subnet extraction" "$WORK_DIR/bad-dns-rule-subnets.json" "domain-only rule sets"

cat >"$WORK_DIR/bad-dns-rule-detour.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "dns", ".type": "section", "enabled": "1", "action": "dns", "dns_server": "9.9.9.9", "dns_detour_enabled": "1", "dns_detour_section": "bypass", "domain_suffix": [ "example.org" ] },
    { ".name": "bypass", ".type": "section", "enabled": "1", "action": "bypass", "domain_suffix": [ "bypass.example" ] }
  ]
}
JSON
assert_rejects "DNS rule unsupported detour" "$WORK_DIR/bad-dns-rule-detour.json" "unsupported action 'bypass'"

cat >"$WORK_DIR/bad-port.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "proxy", ".type": "section", "enabled": "1", "action": "proxy", "ports": [ "70000" ] }
  ]
}
JSON
assert_rejects "bad port" "$WORK_DIR/bad-port.json" "Invalid port condition '70000'"

cat >"$WORK_DIR/bad-subscription.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "proxy", ".type": "section", "enabled": "1", "action": "proxy", "subscription_urls": [ "https://example.com/a| Agent" ] }
  ]
}
JSON
assert_rejects "bad subscription" "$WORK_DIR/bad-subscription.json" "Configure User-Agent in the subscription item settings"

cat >"$WORK_DIR/bad-manual-hwid.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "proxy", ".type": "section", "enabled": "1", "action": "connection" }
  ],
  "subscription_url": [
    {
      ".name": "proxy_sub_1",
      ".type": "subscription_url",
      "section": "proxy",
      "url": "https://example.com/sub.txt",
      "auto_hwid": "0"
    }
  ]
}
JSON
assert_rejects "bad manual HWID" "$WORK_DIR/bad-manual-hwid.json" "manual HWID enabled but HWID is empty"

cat >"$WORK_DIR/bad-latency-url.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "latency_test_url": "ftp://example.com/ping"
  },
  "section": []
}
JSON
assert_rejects "bad latency URL" "$WORK_DIR/bad-latency-url.json" "settings.latency_test_url"

cat >"$WORK_DIR/bad-urltest-tolerance.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "proxy",
      "urltest_enabled": "1",
      "urltest_tolerance": "10001"
    }
  ]
}
JSON
assert_rejects "bad URLTest tolerance" "$WORK_DIR/bad-urltest-tolerance.json" "Use a number from 0 to 10000"

cat >"$WORK_DIR/bad-server-routing-bypass.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "bypass", ".type": "section", "enabled": "1", "action": "bypass" }
  ],
  "server": [
    { ".name": "srv", ".type": "server", "enabled": "1", "routing_mode": "section", "routing_section": "bypass" }
  ]
}
JSON
assert_rejects "bad server routing bypass" "$WORK_DIR/bad-server-routing-bypass.json" "unsupported action 'bypass'"

cat >"$WORK_DIR/bad-server-routing-block.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "block", ".type": "section", "enabled": "1", "action": "block" }
  ],
  "server": [
    { ".name": "srv", ".type": "server", "enabled": "1", "routing_mode": "section", "routing_section": "block" }
  ]
}
JSON
assert_rejects "bad server routing block" "$WORK_DIR/bad-server-routing-block.json" "unsupported action 'block'"

cat >"$WORK_DIR/bad-detour.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "first", ".type": "section", "enabled": "1", "action": "proxy", "outbound_detour_enabled": "1", "outbound_detour_section": "second" },
    { ".name": "second", ".type": "section", "enabled": "1", "action": "proxy", "outbound_detour_enabled": "1", "outbound_detour_section": "first" }
  ]
}
JSON
assert_rejects "bad detour" "$WORK_DIR/bad-detour.json" "creates a cycle"

cat >"$WORK_DIR/bad-list-reference.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "proxy", ".type": "section", "enabled": "1", "action": "proxy", "domain_ip_lists": [ "ftp://example.com/list.lst" ] }
  ]
}
JSON
assert_rejects "bad list reference" "$WORK_DIR/bad-list-reference.json" "Unknown plain list reference"

cat >"$WORK_DIR/bad-country.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "proxy",
      "urltest_enabled": "1",
      "urltest_filter_mode": "include",
      "urltest_include_countries": [ "USA" ]
    }
  ]
}
JSON
assert_rejects "bad country" "$WORK_DIR/bad-country.json" "Invalid country code 'USA'"

for removed_action in byedpi zapret zapret2 olcrtc; do
  cat >"$WORK_DIR/bad-removed-$removed_action.json" <<JSON
{
  "settings": { ".name": "settings", ".type": "settings", "dns_server": [ "77.88.8.8" ], "bootstrap_dns_server": [ "77.88.8.8" ] },
  "section": [
    { ".name": "legacy_sec", ".type": "section", "enabled": "1", "action": "$removed_action", "domain_suffix": [ "example.org" ] }
  ]
}
JSON
  if TACHYON_LIB="$TACHYON_LIB" ucode -L "$TACHYON_LIB" "$VALIDATOR" validate-runtime-fixture "$WORK_DIR/bad-removed-$removed_action.json" "$WORK_DIR/context.json" 2>/dev/null; then
    fail "removed provider action '$removed_action' must be rejected by validator"
  fi
done

# ─── Domain condition validation resilience ─────────────────────────────────
cat >"$WORK_DIR/domain_resilience.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "dns_server": [ "77.88.8.8" ],
    "bootstrap_dns_server": [ "77.88.8.8" ]
  },
  "section": [
    {
      ".name": "resilient_rule",
      ".type": "section",
      "enabled": "1",
      "action": "bypass",
      "domain": "valid.example.com\nfull://\nfull:=====\nfull:(не\nanother.example.org"
    }
  ]
}
JSON

if ! TACHYON_LIB="$TACHYON_LIB" ucode -L "$TACHYON_LIB" "$VALIDATOR" validate-runtime-fixture "$WORK_DIR/domain_resilience.json" "{}" >/dev/null 2>&1; then
  fail "Validator must not abort startup on invalid domain conditions in rules"
fi

# ─── DNS rule shadowed by block/bypass ─────────────────────────────────────
# A dns section can never win over block/bypass (the generator emits those
# rules first), so an inline domain claimed by a block list is dropped silently.
cat >"$WORK_DIR/dns-shadowed.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "block", ".type": "section", "enabled": "1", "action": "block", "community_lists": [ "ads_hagezi_pro" ] },
    { ".name": "XboxDns", ".type": "section", "enabled": "1", "action": "dns", "dns_type": "doh", "dns_server": "https://xbox-dns.ru/dns-query", "domain_suffix": [ "gvt2.com" ] }
  ]
}
JSON
assert_warns "DNS rule shadowed by block list" "$WORK_DIR/dns-shadowed.json" "are evaluated first and win on any overlap"
assert_warns "DNS rule shadow warning names the section" "$WORK_DIR/dns-shadowed.json" "DNS rule 'XboxDns'"
assert_warns "DNS rule shadow warning names the blocker" "$WORK_DIR/dns-shadowed.json" "block"

# bypass shadows the same way
cat >"$WORK_DIR/dns-shadowed-bypass.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "ByPass", ".type": "section", "enabled": "1", "action": "bypass", "domain_suffix": [ "blocked.example" ] },
    { ".name": "dns1", ".type": "section", "enabled": "1", "action": "dns", "dns_server": "9.9.9.9", "domain": [ "blocked.example" ] }
  ]
}
JSON
assert_warns "DNS rule shadowed by bypass rule" "$WORK_DIR/dns-shadowed-bypass.json" "ByPass"

# A disabled blocker cannot shadow anything.
cat >"$WORK_DIR/dns-blocker-disabled.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "block", ".type": "section", "enabled": "0", "action": "block", "community_lists": [ "ads_hagezi_pro" ] },
    { ".name": "dns1", ".type": "section", "enabled": "1", "action": "dns", "dns_server": "9.9.9.9", "domain_suffix": [ "ads.example" ] }
  ]
}
JSON
assert_no_warning "disabled block rule must not warn" "$WORK_DIR/dns-blocker-disabled.json" "are evaluated first and win on any overlap"

# A blocker without any domain matcher cannot shadow a domain either.
cat >"$WORK_DIR/dns-blocker-no-domains.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "block", ".type": "section", "enabled": "1", "action": "block", "ip_cidr": [ "203.0.113.0/24" ] },
    { ".name": "dns1", ".type": "section", "enabled": "1", "action": "dns", "dns_server": "9.9.9.9", "domain_suffix": [ "ads.example" ] }
  ]
}
JSON
assert_no_warning "block rule without domain matchers must not warn" "$WORK_DIR/dns-blocker-no-domains.json" "are evaluated first and win on any overlap"

# Community-list-only DNS sections overlap too, but the overlap is not knowable
# without decompiling the .srs, so they stay silent rather than cry wolf.
cat >"$WORK_DIR/dns-community-only.json" <<'JSON'
{
  "settings": { ".name": "settings", ".type": "settings" },
  "section": [
    { ".name": "block", ".type": "section", "enabled": "1", "action": "block", "community_lists": [ "ads_hagezi_pro" ] },
    { ".name": "dns1", ".type": "section", "enabled": "1", "action": "dns", "dns_server": "9.9.9.9", "community_lists": [ "google_ai" ] }
  ]
}
JSON
assert_no_warning "community-list-only DNS rule must not warn" "$WORK_DIR/dns-community-only.json" "are evaluated first and win on any overlap"

printf 'config validator runtime checks passed\n'
