#!/usr/bin/env bash
#MISE description="Show .deploy-history.jsonl timeline from bigblack (#363 anti-fragile rails)"
#
# Reads ~/eon/opendeviationbar-py/.deploy-history.jsonl on bigblack and
# renders a per-line timeline. Usage:
#   mise run deploy:history              # last 20 entries, compact
#   mise run deploy:history -- 50        # last 50 entries
#   mise run deploy:history -- 20 full   # last 20 entries, full JSON per line

set -euo pipefail

N="${1:-20}"
FORMAT="${2:-compact}"
REMOTE="bigblack-cf"
REMOTE_FILE="~/eon/opendeviationbar-py/.deploy-history.jsonl"

echo "=== #363 deploy history (last $N entries) ==="

if ! ssh "$REMOTE" "test -f $REMOTE_FILE"; then
  echo "No $REMOTE_FILE on $REMOTE yet."
  echo "Will be created on first deploy under the #363 rails."
  exit 0
fi

case "$FORMAT" in
  full)
    ssh "$REMOTE" "tail -n $N $REMOTE_FILE"
    ;;
  compact|*)
    # Compact: ts | tier | status | wheel_ver | wheel_sha | healthy_hb | reason
    ssh "$REMOTE" "tail -n $N $REMOTE_FILE" | \
      uv run --python 3.13 python -c '
import json, sys
for line in sys.stdin:
    line = line.strip()
    if not line:
        continue
    try:
        e = json.loads(line)
    except json.JSONDecodeError:
        print(f"[CORRUPT] {line[:80]}")
        continue
    ts = e.get("ts", "?")
    tier = e.get("tier", "?")
    status = e.get("status", "?")
    ver = e.get("wheel_version", "?")
    sha = (e.get("wheel_sha") or "?")[:8]
    hb = e.get("healthy_hb_count", 0)
    reason = e.get("reason", "")
    icon = {"ok": "\033[32m✓\033[0m", "failed": "\033[31m✗\033[0m"}.get(status, "?")
    print(f"{icon} {ts}  {tier:6} {status:8} {ver:10} {sha}  hb={hb}  {reason}")
'
    ;;
esac
