#!/usr/bin/env python3
"""Gate7G no-op LiveKit participant/audio interface worker.

Purpose:
- Verify that a dispatched LiveKit worker can enter the room lifecycle and attach future audio hooks.
- Do not load STT, TTS, SGLang, LLM, RAG, GPU, models, Redis, Caddy, or external services.
- This is a no-op interface skeleton only.
"""

from __future__ import annotations

import asyncio
import os
from typing import Any

from livekit.agents import JobContext, WorkerOptions, cli


def _env_summary() -> str:
    url = os.environ.get("LIVEKIT_URL", "ws://127.0.0.1:7880")
    key_set = bool(os.environ.get("LIVEKIT_API_KEY", "devkey"))
    secret_set = bool(os.environ.get("LIVEKIT_API_SECRET", "secret"))
    return f"LIVEKIT_URL={url} LIVEKIT_API_KEY_SET={key_set} LIVEKIT_API_SECRET_SET={secret_set}"


def _safe_room_name(ctx: JobContext) -> str:
    room = getattr(ctx, "room", None)
    return getattr(room, "name", "UNKNOWN") if room is not None else "NO_ROOM"


def _attach_noop_handlers(room: Any) -> None:
    """Attach no-op event handlers if the room object supports decorator-style events."""
    if room is None:
        print("GATE7G_ROOM_OBJECT_MISSING", flush=True)
        return

    if hasattr(room, "on"):
        try:
            @room.on("participant_connected")
            def _on_participant_connected(participant: Any) -> None:
                identity = getattr(participant, "identity", "UNKNOWN")
                print(f"GATE7G_EVENT_PARTICIPANT_CONNECTED={identity}", flush=True)

            @room.on("track_subscribed")
            def _on_track_subscribed(track: Any, publication: Any, participant: Any) -> None:
                kind = getattr(track, "kind", "UNKNOWN")
                identity = getattr(participant, "identity", "UNKNOWN")
                print(f"GATE7G_EVENT_TRACK_SUBSCRIBED kind={kind} participant={identity}", flush=True)

            print("GATE7G_NOOP_HANDLERS_ATTACHED", flush=True)
        except Exception as exc:
            print(f"GATE7G_HANDLER_ATTACH_FAIL={type(exc).__name__}:{exc}", flush=True)
    else:
        print("GATE7G_ROOM_ON_API_NOT_AVAILABLE", flush=True)


async def entrypoint(ctx: JobContext) -> None:
    print("GATE7G_ENTRYPOINT_STARTED", flush=True)
    print(_env_summary(), flush=True)
    print(f"GATE7G_JOB_CONTEXT_ROOM={_safe_room_name(ctx)}", flush=True)

    connect_attr = getattr(ctx, "connect", None)
    if callable(connect_attr):
        try:
            await connect_attr()
            print("GATE7G_CTX_CONNECT_OK", flush=True)
        except Exception as exc:
            print(f"GATE7G_CTX_CONNECT_FAIL={type(exc).__name__}:{exc}", flush=True)
            raise
    else:
        print("GATE7G_CTX_CONNECT_NOT_AVAILABLE", flush=True)

    room = getattr(ctx, "room", None)
    _attach_noop_handlers(room)

    # Keep the no-op interface alive briefly so event loop/lifecycle can be observed.
    print("GATE7G_NOOP_AUDIO_INTERFACE_ALIVE", flush=True)
    await asyncio.sleep(3)
    print("GATE7G_ENTRYPOINT_DONE", flush=True)


def main() -> None:
    print("GATE7G_NOOP_WORKER_BOOT", flush=True)
    print(_env_summary(), flush=True)
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))


if __name__ == "__main__":
    main()
