#!/usr/bin/env python3
"""lane_trace — a receipt trail for ONE lease on the shared lane coordinator.

Holds a ticket for a while and logs, every 30 s, what the coordinator says about it:
the heartbeat's `refreshed`, the lane's `held`/`queued` lists, and the ticket's own
state. It exists because on 2026-09-04 a driver mid-render found its ticket gone from
`held`, a probe from the same machine was GRANTED, and nothing on disk said when or
why the lease had left. The trace is that missing evidence: run it alone first, then
with a second copy started a minute later (a different VCLAW_LANE_CLAIM, or a
different VCLAW_MACHINE_ID), and read the two trails side by side.

Never run it while a real render is on the lane — it takes the slot like a render.

    bash scripts/with-shared-queue.sh python3 skills/rap-avatar-mv/scripts/lane_trace.py \
        --minutes 12 --every 30 --out build/lane-trace-a.jsonl

Exit 0 when the ticket was held for the whole window; 1 when it was lost (the trail
says when), 2 when it was never granted.
"""
from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys
import time
import uuid

ROUTE = "seedance-direct"


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--minutes", type=float, default=12.0)
    ap.add_argument("--every", type=float, default=30.0, help="seconds between heartbeats")
    # SHORT LEASE. A trace killed mid-run (macOS low-memory kill, 2026-09-04 21:21) left
    # its ticket HELD and the nimbooda driver queued behind a dead process; at 3600 s
    # that is an hour of lost lane. Ten minutes covers a 5-minute trace and expires fast.
    ap.add_argument("--ttl", type=int, default=600)
    ap.add_argument("--project", default="trace")
    ap.add_argument("--out", default="lane-trace.jsonl")
    ap.add_argument("--main", default=os.environ.get("VCLAW_MAIN") or os.getcwd(),
                    help="repo checkout with a built dist/ (default: cwd)")
    a = ap.parse_args()

    vclaw = os.path.join(a.main, "dist", "cli", "vclaw.js")
    if not os.path.isfile(vclaw):
        print(f"no built CLI at {vclaw}", file=sys.stderr)
        return 2
    account = os.environ.get("VCLAW_LANE_ACCOUNT", "main-unlimited")
    env = dict(os.environ)
    env.setdefault("VCLAW_LANE_CLAIM", f"trace-{os.getpid()}-{uuid.uuid4().hex[:8]}")
    machine = env.get("VCLAW_MACHINE_ID", "?")
    out = open(a.out, "a", encoding="utf-8")

    def lane(verb: str, *args: str) -> dict:
        cmd = [os.environ.get("NODE_BIN", "node"), vclaw, "video", "lane", verb,
               "--route", ROUTE, "--account", account, *args]
        proc = subprocess.run(cmd, cwd=a.main, capture_output=True, text=True, timeout=180, env=env)
        try:
            return json.loads(proc.stdout or "{}")
        except json.JSONDecodeError:
            return {"error": (proc.stderr or proc.stdout)[-300:]}

    def log(event: str, **fields) -> None:
        row = {"t": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "event": event, "machine": machine,
               "claim": env["VCLAW_LANE_CLAIM"], **fields}
        out.write(json.dumps(row) + "\n"); out.flush()
        print(json.dumps(row))

    if a.ttl < a.minutes * 60 + 60:
        print(f"--ttl {a.ttl}s is shorter than the trace ({a.minutes:g} min + 60 s); the lease would expire mid-trace", file=sys.stderr)
        return 2
    grant = lane("await", "--project", a.project, "--prompt-hash", f"trace-{uuid.uuid4().hex[:12]}",
                 "--ttl", str(a.ttl), "--max-wait", "600")
    log("await", reply=grant)
    ticket = grant.get("ticketId")
    if grant.get("status") != "granted" or not ticket:
        return 2

    lost_at = None
    deadline = time.time() + a.minutes * 60
    try:
        while time.time() < deadline:
            time.sleep(a.every)
            hb = lane("heartbeat", "--ticket", ticket)
            st = lane("status")
            held = [t.get("id") or t.get("ticketId") for t in (st.get("held") or [])]
            queued = [t.get("id") or t.get("ticketId") for t in (st.get("queued") or [])]
            mine = next((t for t in (st.get("held") or []) if (t.get("id") or t.get("ticketId")) == ticket), None)
            log("beat", refreshed=hb.get("refreshed"), heartbeat=hb, held=held, queued=queued,
                mine=mine, ours_still_held=ticket in held)
            if ticket not in held and lost_at is None:
                lost_at = time.time()
                log("LOST", ticket=ticket, note="ticket left `held` — read the rows above for the last good beat")
    finally:
        rel = lane("release", "--ticket", ticket, "--outcome", "abandoned" if lost_at else "completed",
                   "--note", f"lane_trace {a.project}: {'ticket left held' if lost_at else 'held for the whole window'}")
        log("release", reply=rel)
    return 1 if lost_at else 0


if __name__ == "__main__":
    sys.exit(main())
