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

BENCHMARK="$TACHYON_LIB/dns/benchmark.uc"
BIN="$ROOT_DIR/tachyon/files/usr/bin/tachyon"
GUARD_WORKER_PID=""

cleanup() {
  if [ -n "$GUARD_WORKER_PID" ]; then
    kill "$GUARD_WORKER_PID" 2>/dev/null || true
    wait "$GUARD_WORKER_PID" 2>/dev/null || true
  fi
  # При регрессии start_async() может создать второй worker тестового fixture.
  local pid_file="$WORK_DIR/guard-state/dns-benchmark.pid"
  local spawned_pid=""
  if [ -f "$pid_file" ]; then
    spawned_pid="$(cat "$pid_file")"
    if [[ "$spawned_pid" =~ ^[0-9]+$ ]] &&
      grep -aqF "$WORK_DIR/guard-lib/dns/benchmark.uc" "/proc/$spawned_pid/cmdline" 2>/dev/null; then
      kill "$spawned_pid" 2>/dev/null || true
    fi
  fi
  rm -rf "$WORK_DIR"
}
trap cleanup EXIT

# ─── 1. Syntax check & module load ──────────────────────────────────────────
ucode -L "$TACHYON_LIB" -c "$BENCHMARK" || fail "benchmark.uc must pass ucode syntax check"
ucode -S -L "$TACHYON_LIB" -c "$BENCHMARK" || fail "benchmark.uc must pass strict ucode syntax check"

# ─── 2. Test candidate pool and structure ───────────────────────────────────
cat >"$WORK_DIR/test_candidates.uc" <<'UCODE'
let benchmark = require("dns.benchmark");

let candidates = benchmark.CANDIDATE_SERVERS;
if (type(candidates) != "array" || length(candidates) < 8) {
    print("ERR: candidate servers array invalid or too small\n");
    exit(1);
}

let has_udp = false;
let has_doh = false;
let has_yandex = false;
let has_cf = false;
let ids = {};
let addresses = {};

for (let c in candidates) {
    if (type(c.id) != "string" || c.id == "" || ids[c.id] ||
        type(c.address) != "string" || c.address == "" || addresses[c.address]) {
        print("ERR: candidate IDs and addresses must be nonempty and unique\n");
        exit(4);
    }
    if ((c.type != "udp" && c.type != "doh") ||
        (c.type == "doh" && !match(c.address, /^https:\/\/[^\/]+/)) ||
        type(c.ip) != "string") {
        print("ERR: invalid candidate transport, DoH URL or fallback IP\n");
        exit(5);
    }
    ids[c.id] = true;
    addresses[c.address] = true;
    if (c.type == "udp") has_udp = true;
    if (c.type == "doh") has_doh = true;
    if (c.provider == "Yandex") has_yandex = true;
    if (c.provider == "Cloudflare") has_cf = true;
}

if (!has_udp || !has_doh) {
    print("ERR: must contain both UDP and DoH servers\n");
    exit(2);
}

if (!has_yandex || !has_cf) {
    print("ERR: must contain Yandex and Cloudflare servers\n");
    exit(3);
}

print("OK\n");
exit(0);
UCODE

ucode -L "$TACHYON_LIB" "$WORK_DIR/test_candidates.uc" | grep -q "OK" ||
  fail "benchmark.uc candidate server pool validation failed"

# ─── 3. Test Recommendation Calculation ─────────────────────────────────────
cat >"$WORK_DIR/test_recommendation.uc" <<'UCODE'
let benchmark = require("dns.benchmark");

// Scenario A: Fast DoH -> Expect DoH recommended with multiple servers
let results_a = [
    { id: "yandex_udp", provider: "Yandex", type: "udp", address: "77.88.8.8", ip: "77.88.8.8", latency: 15, lossPct: 0, status: "excellent", score: 15 },
    { id: "cf_udp", provider: "Cloudflare", type: "udp", address: "1.1.1.1", ip: "1.1.1.1", latency: 20, lossPct: 0, status: "excellent", score: 20 },
    { id: "cf_doh", provider: "Cloudflare", type: "doh", address: "https://cloudflare-dns.com/dns-query", ip: "1.1.1.1", latency: 25, lossPct: 0, status: "excellent", score: 25 },
    { id: "comss_doh", provider: "Comss.one", type: "doh", address: "https://dns.comss.one/dns-query", ip: "92.223.109.31", latency: 30, lossPct: 0, status: "excellent", score: 30 }
];

let rec_a = benchmark.compute_recommendation(results_a);
if (rec_a.dns_type != "doh") {
    print("ERR: Scenario A should recommend DoH, got ", rec_a.dns_type, "\n");
    exit(1);
}
if (length(rec_a.dns_server) < 2) {
    print("ERR: Scenario A should recommend multiple DoH servers\n");
    exit(2);
}
if (rec_a.bootstrap_dns_server[0] != "77.88.8.8") {
    print("ERR: Scenario A bootstrap DNS should be fastest UDP (77.88.8.8)\n");
    exit(3);
}

// Scenario B: Blocked/slow DoH -> Expect UDP recommended
let results_b = [
    { id: "yandex_udp", provider: "Yandex", type: "udp", address: "77.88.8.8", ip: "77.88.8.8", latency: 18, lossPct: 0, status: "excellent", score: 18 },
    { id: "cf_udp", provider: "Cloudflare", type: "udp", address: "1.1.1.1", ip: "1.1.1.1", latency: 35, lossPct: 0, status: "good", score: 35 },
    { id: "cf_doh", provider: "Cloudflare", type: "doh", address: "https://cloudflare-dns.com/dns-query", ip: "1.1.1.1", latency: 350, lossPct: 50, status: "slow", score: 600 }
];

let rec_b = benchmark.compute_recommendation(results_b);
if (rec_b.dns_type != "udp" || rec_b.dns_server[0] != "77.88.8.8") {
    print("ERR: Scenario B should recommend UDP 77.88.8.8\n");
    exit(4);
}

// Scenario C: All failed -> Expect safe failsafe fallback
let results_c = [];
let rec_c = benchmark.compute_recommendation(results_c);
if (rec_c.dns_type != "udp" || rec_c.dns_server[0] != "77.88.8.8" || length(rec_c.dns_server) < 2) {
    print("ERR: Scenario C failsafe failed\n");
    exit(5);
}

// Scenario D: DoH latency higher than UDP, but working -> DoH must STILL be chosen as primary for encryption
let results_d = [
    { id: "yandex_udp", provider: "Yandex", type: "udp", address: "77.88.8.8", ip: "77.88.8.8", latency: 15, lossPct: 0, status: "excellent", score: 15 },
    { id: "cf_udp", provider: "Cloudflare", type: "udp", address: "1.1.1.1", ip: "1.1.1.1", latency: 20, lossPct: 0, status: "excellent", score: 20 },
    { id: "cf_doh", provider: "Cloudflare", type: "doh", address: "https://cloudflare-dns.com/dns-query", ip: "1.1.1.1", latency: 95, lossPct: 0, status: "good", score: 95 }
];
let rec_d = benchmark.compute_recommendation(results_d);
if (rec_d.dns_type != "doh" || rec_d.dns_server[0] != "https://cloudflare-dns.com/dns-query" || rec_d.bootstrap_dns_server[0] != "77.88.8.8") {
    print("ERR: Scenario D failed to prioritize encrypted DoH over UDP\n");
    exit(6);
}

print("OK\n");
exit(0);
UCODE

ucode -L "$TACHYON_LIB" "$WORK_DIR/test_recommendation.uc" | grep -q "OK" ||
  fail "compute_recommendation logic tests failed"

# ─── 3b. Test probe_doh + resolve_host_via_bootstrap runtime regex/parsing ──
mkdir -p "$WORK_DIR/fakebin"
cat >"$WORK_DIR/fakebin/curl" <<'SH'
#!/bin/sh
printf '\n200 0.045 application/dns-message'
exit 0
SH
cat >"$WORK_DIR/fakebin/nslookup" <<'SH'
#!/bin/sh
cat <<'EOF'
Server:		77.88.8.8
Address:	77.88.8.8:53

Non-authoritative answer:
Name:	dns.alidns.com
Address: 223.5.5.5
EOF
exit 0
SH
chmod +x "$WORK_DIR/fakebin/curl" "$WORK_DIR/fakebin/nslookup"

PATH="$WORK_DIR/fakebin:$PATH" ucode -L "$TACHYON_LIB" -e '
let b = require("dns.benchmark");
let ms = b.probe_doh({ address: "https://cloudflare-dns.com/dns-query" }, "google.com", "1.1.1.1");
if (ms != 45) {
    printf("ERR: expected probe_doh=45, got %J\n", ms);
    exit(1);
}
let cand = b.test_candidate(
    { id: "alidns_doh", provider: "AliDNS", type: "doh", address: "https://dns.alidns.com/dns-query", ip: "", tag: "DoH" },
    [ "google.com" ],
    [ "77.88.8.8" ]
);
if (cand.latency != 45 || cand.status == "failed") {
    printf("ERR: expected test_candidate to resolve via bootstrap and probe DoH, got %J\n", cand);
    exit(2);
}
print("OK\n");
' | grep -q "OK" || fail "probe_doh / test_candidate runtime check failed"

# ─── 4. Test CLI help & command registration in /usr/bin/tachyon ─────────────
grep -Fq "dns_benchmark" "$BIN" || fail "/usr/bin/tachyon must register dns_benchmark"
grep -Fq "dns_autotune" "$BIN" || fail "/usr/bin/tachyon must register dns_autotune"
grep -Fq "dns_benchmark_async" "$BIN" || fail "/usr/bin/tachyon must register dns_benchmark_async"
grep -Fq "dns_benchmark_status" "$BIN" || fail "/usr/bin/tachyon must register dns_benchmark_status"
grep -Fq "dns_benchmark_stop" "$BIN" || fail "/usr/bin/tachyon must register dns_benchmark_stop"
grep -Fq "dns_benchmark_apply" "$BIN" || fail "/usr/bin/tachyon must register dns_benchmark_apply"

# ─── 5. Долгий активный worker не должен запускаться повторно ───────────────
# Fixture работает отдельным процессом; DNS/UCI/сервисы в этом тесте не трогаем.
mkdir -p "$WORK_DIR/guard-lib/dns" "$WORK_DIR/guard-state"
printf 'sleep(60000);\n' >"$WORK_DIR/guard-lib/dns/benchmark.uc"
ucode "$WORK_DIR/guard-lib/dns/benchmark.uc" worker &
GUARD_WORKER_PID=$!

ready=false
for ((i = 0; i < 100; i++)); do
  if grep -aqF "$WORK_DIR/guard-lib/dns/benchmark.uc" "/proc/$GUARD_WORKER_PID/cmdline"; then
    ready=true
    break
  fi
  sleep 0.01
done
[ "$ready" = true ] || fail "guard worker fixture did not start"

TACHYON_UI_STATE_DIR="$WORK_DIR/guard-state" ucode -e '
let fs = require("fs");
fs.writefile(getenv("TACHYON_UI_STATE_DIR") + "/dns-benchmark-state.json",
    sprintf("%J", { running: true, started_at: clock()[0] - 180, progress: 55, results: [] }));
'
printf '%s' "$GUARD_WORKER_PID" >"$WORK_DIR/guard-state/dns-benchmark.pid"
cp "$WORK_DIR/guard-state/dns-benchmark-state.json" "$WORK_DIR/guard-state.before"
cp "$WORK_DIR/guard-state/dns-benchmark.pid" "$WORK_DIR/guard-pid.before"

TACHYON_LIB="$WORK_DIR/guard-lib" TACHYON_UI_STATE_DIR="$WORK_DIR/guard-state" \
  ucode -L "$ROOT_DIR/tachyon/files/usr/lib" "$BENCHMARK" benchmark_async >"$WORK_DIR/guard-response.json"
ucode -e '
let fs = require("fs");
let response = json(fs.readfile(ARGV[0]));
if (response.success != true || response.message != "DNS benchmark is already running" ||
    response.state.progress != 55)
    exit(1);
' "$WORK_DIR/guard-response.json" || fail "active worker older than 90 seconds must be reused"
cmp -s "$WORK_DIR/guard-state.before" "$WORK_DIR/guard-state/dns-benchmark-state.json" ||
  fail "duplicate start must preserve benchmark state"
cmp -s "$WORK_DIR/guard-pid.before" "$WORK_DIR/guard-state/dns-benchmark.pid" ||
  fail "duplicate start must preserve worker PID"

printf 'PASS: dns_benchmark\n'
