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

usage() {
  cat <<'EOF'
Usage:
  ./scripts/cir/run_cir_record_sequence_multi_rir_offline.sh \
    [--bundle-root <path>] \
    [--rir <afrinic,apnic,arin,lacnic,ripe>] \
    [--delta-count <n>] \
    [--full-repo] \
    [--out-root <path>] \
    [--rpki-bin <path>]
EOF
}

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
CASE_INFO="$ROOT_DIR/scripts/payload_replay/multi_rir_case_info.py"
SINGLE_SCRIPT="$ROOT_DIR/scripts/cir/run_cir_record_sequence_offline.sh"

BUNDLE_ROOT="/home/yuyr/dev/rust_playground/routinator/bench/multi_rir_demo/runs/20260316-112341-multi-final3"
RIRS="afrinic,apnic,arin,lacnic,ripe"
DELTA_COUNT=2
FULL_REPO=0
OUT_ROOT="$ROOT_DIR/target/replay/cir_sequence_multi_rir_offline_$(date -u +%Y%m%dT%H%M%SZ)"
RPKI_BIN="${RPKI_BIN:-$ROOT_DIR/target/release/rpki}"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --bundle-root) BUNDLE_ROOT="$2"; shift 2 ;;
    --rir) RIRS="$2"; shift 2 ;;
    --delta-count) DELTA_COUNT="$2"; shift 2 ;;
    --full-repo) FULL_REPO=1; shift 1 ;;
    --out-root) OUT_ROOT="$2"; shift 2 ;;
    --rpki-bin) RPKI_BIN="$2"; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "unknown argument: $1" >&2; usage; exit 2 ;;
  esac
done

mkdir -p "$OUT_ROOT"
SUMMARY_JSON="$OUT_ROOT/summary.json"
SUMMARY_MD="$OUT_ROOT/summary.md"

IFS=',' read -r -a RIR_ITEMS <<< "$RIRS"

for rir in "${RIR_ITEMS[@]}"; do
  CASE_JSON="$(python3 "$CASE_INFO" --bundle-root "$BUNDLE_ROOT" --repo-root "$ROOT_DIR" --rir "$rir")"
  TAL_PATH="$(python3 - <<'PY' "$CASE_JSON"
import json,sys
print(json.loads(sys.argv[1])['tal_path'])
PY
)"
  TA_PATH="$(python3 - <<'PY' "$CASE_JSON"
import json,sys
print(json.loads(sys.argv[1])['ta_path'])
PY
)"
  BASE_ARCHIVE="$(python3 - <<'PY' "$CASE_JSON"
import json,sys
print(json.loads(sys.argv[1])['base_archive'])
PY
)"
  BASE_LOCKS="$(python3 - <<'PY' "$CASE_JSON"
import json,sys
print(json.loads(sys.argv[1])['base_locks'])
PY
)"
  DELTA_ARCHIVE="$(python3 - <<'PY' "$CASE_JSON"
import json,sys
print(json.loads(sys.argv[1])['delta_archive'])
PY
)"
  DELTA_LOCKS="$(python3 - <<'PY' "$CASE_JSON"
import json,sys
print(json.loads(sys.argv[1])['delta_locks'])
PY
)"
  OUT_DIR="$OUT_ROOT/$rir"
  args=(
    "$SINGLE_SCRIPT"
    --out-dir "$OUT_DIR" \
    --tal-path "$TAL_PATH" \
    --ta-path "$TA_PATH" \
    --cir-tal-uri "https://example.test/$rir.tal" \
    --payload-replay-archive "$BASE_ARCHIVE" \
    --payload-replay-locks "$BASE_LOCKS" \
    --payload-base-archive "$BASE_ARCHIVE" \
    --payload-base-locks "$BASE_LOCKS" \
    --payload-delta-archive "$DELTA_ARCHIVE" \
    --payload-delta-locks "$DELTA_LOCKS" \
    --delta-count "$DELTA_COUNT" \
    --rpki-bin "$RPKI_BIN"
  )
  if [[ "$FULL_REPO" -ne 1 ]]; then
    args+=(--max-depth 0 --max-instances 1)
  else
    args+=(--full-repo)
  fi
  "${args[@]}"
done

python3 - <<'PY' "$OUT_ROOT" "$RIRS" "$SUMMARY_JSON" "$SUMMARY_MD"
import json, sys
from pathlib import Path
out_root = Path(sys.argv[1])
rirs = [item for item in sys.argv[2].split(',') if item]
summary_json = Path(sys.argv[3])
summary_md = Path(sys.argv[4])
items = []
for rir in rirs:
    root = out_root / rir
    seq = json.loads((root / "sequence.json").read_text(encoding="utf-8"))
    summ = json.loads((root / "summary.json").read_text(encoding="utf-8"))
    items.append({
        "rir": rir,
        "root": str(root),
        "stepCount": len(seq["steps"]),
        "repoBytesDbExists": summ.get("repoBytesDbExists", False),
    })
summary = {"version": 1, "rirs": items}
summary_json.write_text(json.dumps(summary, indent=2), encoding="utf-8")
lines = ["# Multi-RIR Offline CIR Sequence Summary", ""]
for item in items:
    lines.append(f"- `{item['rir']}`: `stepCount={item['stepCount']}` `repoBytesDbExists={item['repoBytesDbExists']}` `root={item['root']}`")
summary_md.write_text("\n".join(lines) + "\n", encoding="utf-8")
PY

echo "done: $OUT_ROOT"
