#!/usr/bin/env python3
"""Launch the auto-cal + rerun panels and KEEP the rerun server up so
Cameron can open the web viewer from his Mac and eyeball the alignment.

Exits cleanly after 120 seconds OR on Ctrl-C, whichever comes first.
"""
# Force MuJoCo EGL BEFORE any mujoco import.
import os
os.environ.setdefault("MUJOCO_GL", "egl")
os.environ.setdefault("PYOPENGL_PLATFORM", "egl")

import json
import signal
import sys
import time
from pathlib import Path

for p in ("/home/robot-lab/raiden_internal/third_party/exo_redo",):
    if p not in sys.path:
        sys.path.insert(0, p)

from raiden._config import CAMERA_CONFIG
from raiden.record_testing import (
    _patch_scene_zed_hd1080, _run_auto_calibration,
    _downshift_scene_cams_to_hd720)
from raiden.recorder import load_cameras_from_config
from raiden.calibration.exo_auto_viz import log_calibration_overlay_panels

# ---- setup ----
with open(CAMERA_CONFIG) as f:
    cfg = json.load(f)
# Only bump scene_camera (far) — ego stays at HD720 where it detects.
HD1080_NAMES = {"scene_camera"}
scene_serials = {int(e["serial"]) for name, e in cfg.items()
                 if isinstance(e, dict) and name in HD1080_NAMES
                 and e.get("type") == "zed"}
print(f"[live] HD1080 cams: names={HD1080_NAMES} serials={sorted(scene_serials)}")

_patch_scene_zed_hd1080(scene_serials)
print("[live] opening cameras at HD1080 for cal window...")
cameras = load_cameras_from_config(CAMERA_CONFIG)

# Run auto-cal against /tmp (not overwriting production file)
tmp_out = Path("/tmp/auto_cal_test.json")
tmp_out.unlink(missing_ok=True)
ok = _run_auto_calibration(CAMERA_CONFIG, str(tmp_out), cameras,
                            n_frames_per_cam=15)
print(f"[live] auto-cal: {ok}")

print("[live] downshifting scene cams to HD720...")
_downshift_scene_cams_to_hd720(cameras, scene_serials)

# ---- log panels + keep alive ----
print("\n[live] logging calibration overlay panels to rerun...")
logged = log_calibration_overlay_panels(
    cameras, CAMERA_CONFIG, str(tmp_out),
    robot_controller=None, rerun_port=9877)
print(f"[live] panels logged: {logged}")

if not logged:
    print("[live] panels did not log — nothing to view; exiting")
    for cam in cameras:
        try: cam.close()
        except Exception: pass
    sys.exit(1)

print("\n" + "=" * 68)
print("  📺  RERUN VIEWER — open ONE of these in your Mac browser:")
print("=" * 68)
print("    http://100.123.182.78:9877       (russet tailscale IP)")
print("    http://100.123.182.78:9878       (grpc port — try if 9877 fails)")
print("  OR via SSH tunnel from your Mac:")
print("    ssh -L 9877:localhost:9877 russet")
print("    then open http://localhost:9877")
print("=" * 68)
print("\n  Waiting up to 180 seconds for you to view (Ctrl-C to exit early)...")

# Handle SIGINT gracefully so we always close cameras.
_stop = [False]
def _sigint(sig, frame):
    print("\n[live] SIGINT — winding down...")
    _stop[0] = True
signal.signal(signal.SIGINT, _sigint)

t0 = time.time()
while (time.time() - t0) < 600 and not _stop[0]:
    time.sleep(1)

print(f"\n[live] closing after {int(time.time() - t0)}s")
for cam in cameras:
    try: cam.close()
    except Exception: pass
print("[live] done.")
