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

usage() {
  cat <<'EOF'
Usage:
  ./scripts/cir/run_cir_replay_sequence_routinator.sh \
    --sequence-root <path> \
    [--routinator-root <path>] \
    [--routinator-bin <path>] \
    [--real-rsync-bin <path>]
EOF
}

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
SEQUENCE_ROOT=""
ROUTINATOR_ROOT="${ROUTINATOR_ROOT:-/home/yuyr/dev/rust_playground/routinator}"
ROUTINATOR_BIN="${ROUTINATOR_BIN:-$ROUTINATOR_ROOT/target/debug/routinator}"
REAL_RSYNC_BIN="${REAL_RSYNC_BIN:-/usr/bin/rsync}"
STEP_SCRIPT="$ROOT_DIR/scripts/cir/run_cir_replay_routinator.sh"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --sequence-root) SEQUENCE_ROOT="$2"; shift 2 ;;
    --routinator-root) ROUTINATOR_ROOT="$2"; shift 2 ;;
    --routinator-bin) ROUTINATOR_BIN="$2"; shift 2 ;;
    --real-rsync-bin) REAL_RSYNC_BIN="$2"; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "unknown argument: $1" >&2; usage; exit 2 ;;
  esac
done

[[ -n "$SEQUENCE_ROOT" ]] || { usage >&2; exit 2; }

SEQUENCE_ROOT="$(python3 - <<'PY' "$SEQUENCE_ROOT"
from pathlib import Path
import sys
print(Path(sys.argv[1]).resolve())
PY
)"

SUMMARY_JSON="$SEQUENCE_ROOT/sequence-summary-routinator.json"
SUMMARY_MD="$SEQUENCE_ROOT/sequence-summary-routinator.md"

python3 - <<'PY' "$SEQUENCE_ROOT" "$SUMMARY_JSON" "$SUMMARY_MD" "$STEP_SCRIPT" "$ROUTINATOR_ROOT" "$ROUTINATOR_BIN" "$REAL_RSYNC_BIN"
import json
import subprocess
import sys
from pathlib import Path

sequence_root = Path(sys.argv[1])
summary_json = Path(sys.argv[2])
summary_md = Path(sys.argv[3])
step_script = Path(sys.argv[4])
routinator_root = sys.argv[5]
routinator_bin = sys.argv[6]
real_rsync_bin = sys.argv[7]

sequence = json.loads((sequence_root / "sequence.json").read_text(encoding="utf-8"))
repo_bytes_db = sequence_root / sequence["repoBytesDbPath"]
steps = sequence["steps"]
results = []
all_match = True

for step in steps:
    step_id = step["stepId"]
    out_dir = sequence_root / "replay-routinator" / step_id
    out_dir.parent.mkdir(parents=True, exist_ok=True)
    cmd = [
        str(step_script),
        "--cir",
        str(sequence_root / step["cirPath"]),
        "--out-dir",
        str(out_dir),
        "--reference-ccr",
        str(sequence_root / step["ccrPath"]),
        "--routinator-root",
        routinator_root,
        "--routinator-bin",
        routinator_bin,
        "--real-rsync-bin",
        real_rsync_bin,
    ]
    cmd.extend(["--repo-bytes-db", str(repo_bytes_db)])
    proc = subprocess.run(cmd, capture_output=True, text=True)
    if proc.returncode != 0:
        raise SystemExit(
            f"routinator sequence replay failed for {step_id}: stdout={proc.stdout} stderr={proc.stderr}"
        )
    compare = json.loads((out_dir / "compare-summary.json").read_text(encoding="utf-8"))
    match = bool(compare["vrps"]["match"]) and bool(compare["vaps"]["match"])
    all_match = all_match and match
    results.append(
        {
            "stepId": step_id,
            "kind": step["kind"],
            "validationTime": step["validationTime"],
            "outDir": str(out_dir),
            "comparePath": str(out_dir / "compare-summary.json"),
            "compareMode": compare.get("compareMode"),
            "talCount": compare.get("talCount"),
            "talPaths": compare.get("talPaths", []),
            "match": match,
            "compare": compare,
        }
    )

summary = {
    "version": 1,
    "participant": "routinator",
    "sequenceRoot": str(sequence_root),
    "stepCount": len(results),
    "allMatch": all_match,
    "steps": results,
}
summary_json.write_text(json.dumps(summary, indent=2), encoding="utf-8")
lines = [
    "# Routinator CIR Sequence Replay Summary",
    "",
    f"- `sequence_root`: `{sequence_root}`",
    f"- `step_count`: `{len(results)}`",
    f"- `all_match`: `{all_match}`",
    "",
    "| Step | Kind | TALs | Compare mode | VRP actual/ref | VRP match | VAP actual/ref | VAP match |",
    "| --- | --- | ---: | --- | --- | --- | --- | --- |",
]
for item in results:
    compare = item["compare"]
    lines.append(
        "| {step} | {kind} | {tal_count} | {compare_mode} | {va}/{vr} | {vm} | {aa}/{ar} | {am} |".format(
            step=item["stepId"],
            kind=item["kind"],
            tal_count=item.get("talCount") if item.get("talCount") is not None else "-",
            compare_mode=item.get("compareMode") or "-",
            va=compare["vrps"]["actual"],
            vr=compare["vrps"]["reference"],
            vm=compare["vrps"]["match"],
            aa=compare["vaps"]["actual"],
            ar=compare["vaps"]["reference"],
            am=compare["vaps"]["match"],
        )
    )
summary_md.write_text("\n".join(lines), encoding="utf-8")
PY

echo "done: $SEQUENCE_ROOT"
