import json
import time
from pathlib import Path

ART = Path("/opt/ai-avatar-demo/work/gate602_m4a_r2_artifacts")
ART.mkdir(parents=True, exist_ok=True)
room = "gate602-m4a-r2-room"
browser_identity = "mars-160-browser"
worker_identity = "gate602-m4a-r2-worker"
ts = int(time.time())
result = {
    "room": room,
    "browser_identity": browser_identity,
    "worker_identity": worker_identity,
    "timestamp": ts,
    "livekit_url_local": "ws://127.0.0.1:7880",
    "livekit_url_for_160_candidate": "ws://192.168.0.2:7880",
    "token_method_or_blocker": "devkey/secret available only from LiveKit --dev log; .env not read",
    "browser_reachability_note": "server log shows bindAddresses 127.0.0.1 and ::1, so 160 browser direct room join is not proven",
}
try:
    from livekit import api
    browser_token = (
        api.AccessToken("devkey", "secret")
        .with_identity(browser_identity)
        .with_name(browser_identity)
        .with_grants(api.VideoGrants(room_join=True, room=room))
        .to_jwt()
    )
    worker_token = (
        api.AccessToken("devkey", "secret")
        .with_identity(worker_identity)
        .with_name(worker_identity)
        .with_grants(api.VideoGrants(room_join=True, room=room))
        .to_jwt()
    )
    result["token_generation"] = "PASS"
    result["browser_token_length"] = len(browser_token)
    result["worker_token_length"] = len(worker_token)
except Exception as exc:
    result["token_generation"] = "FAILED"
    result["token_error"] = type(exc).__name__ + ": " + str(exc)

path = ART / f"m4a_r2_room_contract_{ts}.json"
path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
print("M4A_R2_ROOM_CONTRACT=" + str(path))
print("M4A_R2_TOKEN_GENERATION=" + result.get("token_generation", "UNKNOWN"))
print(json.dumps(result, ensure_ascii=False))
