# shellcheck shell=bash

_okstra_ctl_batch() {
  if [[ $# -lt 1 ]]; then
    printf 'batch: missing subcommand (list|status)\n' >&2; exit 2
  fi
  local sub="$1"; shift
  case "$sub" in
    list)
      OKSTRA_HOME_RESOLVED="$(okstra_central_home)" python3 - <<'PY'
import json, os
from pathlib import Path
home = Path(os.environ["OKSTRA_HOME_RESOLVED"])
batches = sorted((home / "batches").glob("*.json"))
print(f"{'BATCH-ID':<24}  {'CREATED':<22}  {'SPAWNED':>7}  {'SKIPPED':>7}")
for b in batches:
    m = json.loads(b.read_text())
    s = m.get("summary", {})
    print(f"{m['batchId']:<24}  {m['createdAt']:<22}  "
          f"{s.get('spawned', 0):>7}  {s.get('skipped', 0):>7}")
PY
      ;;
    status)
      if [[ $# -lt 1 ]]; then
        printf 'batch status: missing <batch-id>\n' >&2; exit 2
      fi
      OKSTRA_HOME_RESOLVED="$(okstra_central_home)" \
      OKSTRA_CTL_LIB_DIR="$SCRIPT_DIR" \
      OK_BID="$1" python3 - <<'PY'
import json, os, sys
sys.path.insert(0, os.environ["OKSTRA_CTL_LIB_DIR"])
from pathlib import Path
from okstra_ctl import find_row_by_run_id
home = Path(os.environ["OKSTRA_HOME_RESOLVED"])
target = home / "batches" / f"{os.environ['OK_BID']}.json"
if not target.is_file():
    print(f"batch: not found: {os.environ['OK_BID']}", file=sys.stderr); sys.exit(2)
m = json.loads(target.read_text())
print(f"batchId   : {m['batchId']}")
print(f"createdAt : {m['createdAt']}")
print(f"summary   : {m['summary']}")
print()
print(f"{'SPAWN':<10}  {'LIVE':<11}  {'NEW-RUN-ID':<55}  {'SESSION-NAME'}")
for it in m["items"]:
    spawn_status = it["status"]
    new_run_id = it.get("newRunId") or "-"
    # 현재 인덱스(active+recent+archive)에서 live 상태를 조회한다.
    live = "-"
    if it.get("newRunId"):
        live_row = find_row_by_run_id(home, it["newRunId"])
        if live_row is not None:
            live = live_row.get("status", "-")
    print(f"{spawn_status:<10}  {live:<11}  "
          f"{new_run_id:<55}  {it.get('sessionName') or '-'}")
PY
      ;;
    *) printf 'batch: unknown subcommand: %s\n' "$sub" >&2; exit 2 ;;
  esac
}
