#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$ROOT_DIR"

RIRS=""
OUT_ROOT=""
BASE_VALIDATION_TIME=""
DELTA_VALIDATION_TIME=""
HTTP_TIMEOUT_SECS=""
RSYNC_TIMEOUT_SECS=""
RSYNC_MIRROR_ROOT=""
MAX_DEPTH=""
MAX_INSTANCES=""
NO_BUILD=0
BIN_DIR="target/release"

usage() {
  cat <<'EOF'
Usage:
  ./scripts/replay_bundle/run_live_bundle_record_multi_rir.sh \
    --rir <afrinic,apnic,...> \
    [--out-root <path>] \
    [--base-validation-time <rfc3339>] \
    [--delta-validation-time <rfc3339>] \
    [--http-timeout-secs <n>] \
    [--rsync-timeout-secs <n>] \
    [--rsync-mirror-root <path>] \
    [--max-depth <n>] \
    [--max-instances <n>] \
    [--bin-dir <path>] \
    [--no-build]
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --rir) RIRS="${2:?}"; shift 2 ;;
    --out-root) OUT_ROOT="${2:?}"; shift 2 ;;
    --base-validation-time) BASE_VALIDATION_TIME="${2:?}"; shift 2 ;;
    --delta-validation-time) DELTA_VALIDATION_TIME="${2:?}"; shift 2 ;;
    --http-timeout-secs) HTTP_TIMEOUT_SECS="${2:?}"; shift 2 ;;
    --rsync-timeout-secs) RSYNC_TIMEOUT_SECS="${2:?}"; shift 2 ;;
    --rsync-mirror-root) RSYNC_MIRROR_ROOT="${2:?}"; shift 2 ;;
    --max-depth) MAX_DEPTH="${2:?}"; shift 2 ;;
    --max-instances) MAX_INSTANCES="${2:?}"; shift 2 ;;
    --bin-dir) BIN_DIR="${2:?}"; shift 2 ;;
    --no-build) NO_BUILD=1; shift ;;
    --help|-h) usage; exit 0 ;;
    *) echo "unknown argument: $1" >&2; usage >&2; exit 2 ;;
  esac
done

if [[ -z "$RIRS" ]]; then
  usage >&2
  exit 2
fi

RUN_TAG="$(date -u +%Y%m%dT%H%M%SZ)"
if [[ -z "$OUT_ROOT" ]]; then
  OUT_ROOT="target/replay/live_bundle_matrix_${RUN_TAG}"
fi
mkdir -p "$OUT_ROOT"

resolve_tal_path() {
  case "$1" in
    afrinic) printf 'tests/fixtures/tal/afrinic.tal' ;;
    apnic) printf 'tests/fixtures/tal/apnic-rfc7730-https.tal' ;;
    arin) printf 'tests/fixtures/tal/arin.tal' ;;
    lacnic) printf 'tests/fixtures/tal/lacnic.tal' ;;
    ripe) printf 'tests/fixtures/tal/ripe-ncc.tal' ;;
    *) echo "unsupported rir: $1" >&2; exit 2 ;;
  esac
}

resolve_ta_path() {
  case "$1" in
    afrinic) printf 'tests/fixtures/ta/afrinic-ta.cer' ;;
    apnic) printf 'tests/fixtures/ta/apnic-ta.cer' ;;
    arin) printf 'tests/fixtures/ta/arin-ta.cer' ;;
    lacnic) printf 'tests/fixtures/ta/lacnic-ta.cer' ;;
    ripe) printf 'tests/fixtures/ta/ripe-ncc-ta.cer' ;;
    *) echo "unsupported rir: $1" >&2; exit 2 ;;
  esac
}

SUMMARY_JSON="$OUT_ROOT/summary.json"
SUMMARY_MD="$OUT_ROOT/summary.md"

python3 - "$SUMMARY_JSON" "$RUN_TAG" <<'PY'
import json, sys
out, run_tag = sys.argv[1:]
with open(out, "w") as fh:
    json.dump({"runTag": run_tag, "results": []}, fh, indent=2)
PY

IFS=',' read -r -a RIR_LIST <<< "$RIRS"
for raw_rir in "${RIR_LIST[@]}"; do
  rir="$(printf '%s' "$raw_rir" | tr '[:upper:]' '[:lower:]' | xargs)"
  [[ -n "$rir" ]] || continue
  tal_path="$(resolve_tal_path "$rir")"
  ta_path="$(resolve_ta_path "$rir")"
  out_dir="$OUT_ROOT/${rir}_live_bundle_${RUN_TAG}"
  cmd=(
    ./scripts/replay_bundle/run_live_bundle_record.sh
    --rir "$rir"
    --out-dir "$out_dir"
    --tal-path "$tal_path"
    --ta-path "$ta_path"
    --trust-anchor "$rir"
    --bin-dir "$BIN_DIR"
  )
  [[ -n "$BASE_VALIDATION_TIME" ]] && cmd+=(--base-validation-time "$BASE_VALIDATION_TIME")
  [[ -n "$DELTA_VALIDATION_TIME" ]] && cmd+=(--delta-validation-time "$DELTA_VALIDATION_TIME")
  [[ -n "$HTTP_TIMEOUT_SECS" ]] && cmd+=(--http-timeout-secs "$HTTP_TIMEOUT_SECS")
  [[ -n "$RSYNC_TIMEOUT_SECS" ]] && cmd+=(--rsync-timeout-secs "$RSYNC_TIMEOUT_SECS")
  [[ -n "$RSYNC_MIRROR_ROOT" ]] && cmd+=(--rsync-mirror-root "$RSYNC_MIRROR_ROOT")
  [[ -n "$MAX_DEPTH" ]] && cmd+=(--max-depth "$MAX_DEPTH")
  [[ -n "$MAX_INSTANCES" ]] && cmd+=(--max-instances "$MAX_INSTANCES")
  [[ "$NO_BUILD" -eq 1 ]] && cmd+=(--no-build)
  "${cmd[@]}"

  python3 - "$SUMMARY_JSON" "$rir" "$out_dir" <<'PY'
import json, pathlib, sys
summary_path, rir, out_dir = sys.argv[1:]
summary = json.loads(pathlib.Path(summary_path).read_text())
bundle = json.loads(pathlib.Path(out_dir, rir, "bundle.json").read_text())
verification = json.loads(pathlib.Path(out_dir, rir, "verification.json").read_text())
summary["results"].append({
    "rir": rir,
    "outDir": out_dir,
    "baseVrpCount": bundle["baseVrpCount"],
    "deltaVrpCount": bundle["deltaVrpCount"],
    "baseVapCount": bundle["baseVapCount"],
    "deltaVapCount": bundle["deltaVapCount"],
    "baseSelfReplayOk": verification["base"]["capture"]["selfReplayOk"],
    "deltaSelfReplayOk": verification["delta"]["capture"]["selfReplayOk"],
})
pathlib.Path(summary_path).write_text(json.dumps(summary, indent=2))
PY
done

python3 - "$SUMMARY_JSON" "$SUMMARY_MD" <<'PY'
import json, pathlib, sys
summary = json.loads(pathlib.Path(sys.argv[1]).read_text())
out = pathlib.Path(sys.argv[2])
lines = [
    "# Multi-RIR Live Bundle Record Summary",
    "",
    f"- runTag: `{summary['runTag']}`",
    "",
    "| rir | base_vrps | delta_vrps | base_vaps | delta_vaps | base_self_replay | delta_self_replay | out_dir |",
    "|---|---:|---:|---:|---:|---|---|---|",
]
for item in summary["results"]:
    lines.append(
        f"| {item['rir']} | {item['baseVrpCount']} | {item['deltaVrpCount']} | "
        f"{item['baseVapCount']} | {item['deltaVapCount']} | "
        f"{str(item['baseSelfReplayOk']).lower()} | {str(item['deltaSelfReplayOk']).lower()} | "
        f"`{item['outDir']}` |"
    )
out.write_text("\n".join(lines) + "\n")
PY

echo "$OUT_ROOT"
