"""
LiveKit token generation endpoint.

Generates a LiveKit room JWT for voice calls. The token includes:
- A unique room name and participant identity
- Agent dispatch configuration (auto-spawns voice-agent)
- The caller's auth header in dispatch metadata (for agent-service auth)
"""

import json
import uuid
from typing import Optional

from fastapi import APIRouter, Request
from pydantic import BaseModel

from livekit import api as livekit_api

from ..config.settings import settings

router = APIRouter()


class TokenRequest(BaseModel):
    tts_voice: Optional[str] = None
    tts_style: Optional[str] = None
    engine_type: Optional[str] = None


@router.post("/livekit/token")
async def create_livekit_token(request: Request, body: TokenRequest = TokenRequest()):
    """Generate a LiveKit room token for a voice call session.

    The caller's Authorization header and optional TTS preferences are
    embedded in the agent dispatch metadata so the voice-agent can use them.
    """
    auth_header = request.headers.get("authorization", "")

    room_name = f"voice-{uuid.uuid4().hex[:12]}"
    participant_identity = f"user-{uuid.uuid4().hex[:8]}"

    # Build metadata with auth + optional voice preferences
    metadata: dict = {"auth_header": auth_header}
    if body.tts_voice:
        metadata["tts_voice"] = body.tts_voice
    if body.tts_style:
        metadata["tts_style"] = body.tts_style
    if body.engine_type:
        metadata["engine_type"] = body.engine_type

    token = (
        livekit_api.AccessToken(settings.livekit_api_key, settings.livekit_api_secret)
        .with_identity(participant_identity)
        .with_name("User")
        .with_grants(
            livekit_api.VideoGrants(
                room_join=True,
                room=room_name,
                can_publish=True,
                can_subscribe=True,
                can_publish_data=True,
            )
        )
        .with_room_config(
            livekit_api.RoomConfiguration(
                agents=[
                    livekit_api.RoomAgentDispatch(
                        agent_name="voice-agent",
                        metadata=json.dumps(metadata),
                    )
                ],
            )
        )
    )

    return {
        "token": token.to_jwt(),
        "room_name": room_name,
        "livekit_url": settings.livekit_ws_url,
    }
