#!/usr/bin/env python3
"""Gate7E minimal LiveKit Agent worker stub.

Purpose:
- Verify that the installed LiveKit Agents framework can start a minimal worker shell.
- Do not load heavy transport, caching, or LLM engines.
- This file is for local smoke testing only.

Expected smoke environment:
- LIVEKIT_URL=ws://127.0.0.1:7880
- LIVEKIT_API_KEY=devkey
- LIVEKIT_API_SECRET=secret
"""

from __future__ import annotations

import os
import signal
import sys
from typing import Any

from livekit.agents import JobContext, WorkerOptions, cli


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


async def entrypoint(ctx: JobContext) -> None:
    """Minimal worker entrypoint.

    It intentionally does not connect heavy AI models or tools.
    If LiveKit starts a job, this proves the worker shell can enter the job context.
    """
    print("GATE7E_ENTRYPOINT_STARTED", flush=True)
    print(_redacted_env_summary(), flush=True)

    room = getattr(ctx, "room", None)
    room_name = getattr(room, "name", "UNKNOWN") if room is not None else "NO_ROOM"
    print(f"GATE7E_JOB_CONTEXT_ROOM={room_name}", flush=True)

    # Keep the entrypoint lightweight and immediately return.
    print("GATE7E_ENTRYPOINT_DONE", flush=True)


def main() -> None:
    print("GATE7E_MINIMAL_WORKER_BOOT", flush=True)
    print(_redacted_env_summary(), flush=True)

    # cli.run_app owns the worker loop. The caller must run this script under timeout.
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))


if __name__ == "__main__":
    main()