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

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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
SEQUENCE_ROOT=""
DROP_BIN="${DROP_BIN:-$ROOT_DIR/target/release/cir_drop_report}"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --sequence-root) SEQUENCE_ROOT="$2"; shift 2 ;;
    --drop-bin) DROP_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; }

python3 - <<'PY' "$SEQUENCE_ROOT" "$DROP_BIN"
import json
import subprocess
import sys
from pathlib import Path

sequence_root = Path(sys.argv[1]).resolve()
drop_bin = sys.argv[2]
sequence = json.loads((sequence_root / "sequence.json").read_text(encoding="utf-8"))
repo_bytes_db = sequence_root / sequence["repoBytesDbPath"]

summaries = []
for step in sequence["steps"]:
    step_id = step["stepId"]
    out_dir = sequence_root / "drop" / step_id
    out_dir.mkdir(parents=True, exist_ok=True)
    cmd = [
        drop_bin,
        "--cir",
        str(sequence_root / step["cirPath"]),
        "--ccr",
        str(sequence_root / step["ccrPath"]),
        "--report-json",
        str(sequence_root / step["reportPath"]),
        "--json-out",
        str(out_dir / "drop.json"),
        "--md-out",
        str(out_dir / "drop.md"),
    ]
    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"drop report failed for {step_id}: stdout={proc.stdout} stderr={proc.stderr}"
        )
    result = json.loads((out_dir / "drop.json").read_text(encoding="utf-8"))
    summaries.append(
        {
            "stepId": step_id,
            "droppedVrpCount": result["summary"]["droppedVrpCount"],
            "droppedObjectCount": result["summary"]["droppedObjectCount"],
            "reportPath": str(out_dir / "drop.json"),
        }
    )

summary = {"version": 1, "steps": summaries}
(sequence_root / "drop-summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
PY

echo "done: $SEQUENCE_ROOT"
