"""Combined HTTP static file + token server for R1 creations.

Serves the files in ./creation and exposes a /getToken endpoint that mints
LiveKit access tokens with a RoomConfiguration so the named agent (r1-claude)
is dispatched into the room.

Run it with the agent's uv environment (which already has livekit-api):

    cd agent && uv run python ../web-server.py

LiveKit credentials are read from the environment, falling back to the values
the LiveKit CLI wrote into agent/.env.local.
"""

import json
import os
import time
from http.server import HTTPServer, SimpleHTTPRequestHandler
from pathlib import Path

from livekit import api
from livekit.protocol.room import RoomConfiguration


def _load_env_local() -> None:
    """Populate LIVEKIT_* from agent/.env.local if not already in the env."""
    env_file = Path(__file__).resolve().parent / "agent" / ".env.local"
    if not env_file.exists():
        return
    for line in env_file.read_text().splitlines():
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, _, value = line.partition("=")
        key = key.strip()
        value = value.strip().strip('"').strip("'")
        os.environ.setdefault(key, value)


_load_env_local()

# Final fallbacks (the CLI normally fills these into agent/.env.local).
os.environ.setdefault("LIVEKIT_URL", "wss://rabbit-r1-uxycy3s3.livekit.cloud")
os.environ.setdefault("LIVEKIT_API_KEY", "YOUR_API_KEY")
os.environ.setdefault("LIVEKIT_API_SECRET", "YOUR_API_SECRET")

DIR = os.path.dirname(os.path.abspath(__file__))
os.chdir(DIR)


class Handler(SimpleHTTPRequestHandler):
    def do_POST(self):
        if self.path == "/getToken":
            self._handle_token()
        else:
            self.send_error(404)

    def do_OPTIONS(self):
        self.send_response(200)
        self._cors_headers()
        self.end_headers()

    def _handle_token(self):
        length = int(self.headers.get("Content-Length", 0))
        body = json.loads(self.rfile.read(length)) if length else {}

        room_name = body.get("room_name") or f"r1-room-{int(time.time())}"
        identity = body.get("participant_identity") or f"r1-user-{int(time.time())}"

        token = (
            api.AccessToken(
                os.environ["LIVEKIT_API_KEY"], os.environ["LIVEKIT_API_SECRET"]
            )
            .with_identity(identity)
            .with_name(body.get("participant_name") or "R1 User")
            .with_grants(
                api.VideoGrants(
                    room_join=True,
                    room=room_name,
                    can_publish=True,
                    can_subscribe=True,
                )
            )
        )

        if body.get("room_config"):
            rc_data = body["room_config"]
            room_config = RoomConfiguration()
            for a in rc_data.get("agents", []):
                dispatch = room_config.agents.add()
                dispatch.agent_name = a.get("agent_name", "")
            token = token.with_room_config(room_config)

        resp = json.dumps(
            {
                "server_url": os.environ["LIVEKIT_URL"],
                "participant_token": token.to_jwt(),
            }
        ).encode()

        self.send_response(201)
        self.send_header("Content-Type", "application/json")
        self._cors_headers()
        self.end_headers()
        self.wfile.write(resp)

    def _cors_headers(self):
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")

    def log_message(self, fmt, *args):
        print(f"[server] {args[0]}")


if __name__ == "__main__":
    server = HTTPServer(("0.0.0.0", 8081), Handler)
    print("Server running on http://0.0.0.0:8081 (static files + token endpoint)")
    server.serve_forever()
