#!/usr/bin/env python3
"""Test the rerun-panel path of record_testing.py end-to-end WITHOUT
starting robot / teleop. Robot joint state defaults to home pose (we
pass robot_controller=None). Panel logging fires + we verify no
exception + rerun server binds.
"""
# Force MuJoCo EGL backend BEFORE mujoco is imported anywhere in the chain.
import os
os.environ.setdefault("MUJOCO_GL", "egl")
os.environ.setdefault("PYOPENGL_PLATFORM", "egl")

import json
import sys
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

with open(CAMERA_CONFIG) as f:
    cfg = json.load(f)
scene_serials = {int(e["serial"]) for e in cfg.values()
                 if isinstance(e, dict) and e.get("role") == "scene"
                 and e.get("type") == "zed"}
print(f"[test] scene serials: {sorted(scene_serials)}")

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

# Run auto-cal against /tmp so we don't overwrite 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"[test] auto-cal returned: {ok}")

# Downshift to HD720 (matches record_testing.py flow)
print("[test] downshifting scene cams to HD720...")
_downshift_scene_cams_to_hd720(cameras, scene_serials)

# NEW: log rerun panels with home-pose joints (robot_controller=None)
print("\n[test] 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"[test] panels logged: {logged}")

for cam in cameras:
    try: cam.close()
    except Exception: pass
print("[test] cameras closed.")
