"""Chat and conversation API routes."""

from __future__ import annotations

from fastapi import APIRouter, Request, HTTPException
from pydantic import BaseModel

from conversations.conversation_manager import ConversationManager

router = APIRouter(tags=["chat"])


class ChatRequest(BaseModel):
    question: str
    conversation_id: str | None = None


class ConversationUpdate(BaseModel):
    title: str


@router.get("/conversations")
async def list_conversations(request: Request, limit: int = 50):
    cm = ConversationManager(request.app.state.db)
    return await cm.list_conversations(limit=limit)


@router.post("/conversations")
async def create_conversation(request: Request, body: ConversationUpdate | None = None):
    cm = ConversationManager(request.app.state.db)
    title = body.title if body else "New Conversation"
    return await cm.create_conversation(title)


@router.get("/conversations/{conversation_id}")
async def get_conversation(request: Request, conversation_id: str):
    cm = ConversationManager(request.app.state.db)
    conv = await cm.get_conversation(conversation_id)
    if not conv:
        raise HTTPException(404, "Conversation not found")
    messages = await cm.get_messages(conversation_id)
    return {**conv, "messages": messages}


@router.put("/conversations/{conversation_id}")
async def update_conversation(request: Request, conversation_id: str, body: ConversationUpdate):
    cm = ConversationManager(request.app.state.db)
    return await cm.update_conversation(conversation_id, body.title)


@router.delete("/conversations/{conversation_id}")
async def delete_conversation(request: Request, conversation_id: str):
    cm = ConversationManager(request.app.state.db)
    await cm.delete_conversation(conversation_id)
    return {"status": "deleted"}


@router.get("/conversations/{conversation_id}/messages")
async def get_messages(request: Request, conversation_id: str):
    cm = ConversationManager(request.app.state.db)
    return await cm.get_messages(conversation_id)


@router.post("/chat")
async def chat(request: Request, body: ChatRequest):
    """Non-streaming chat endpoint. For streaming, use WebSocket."""
    from orchestrator.orchestrator import Orchestrator

    settings = request.app.state.settings
    db = request.app.state.db
    orchestrator = Orchestrator(settings, db)

    events = []
    async for event in orchestrator.process_question(body.question, body.conversation_id):
        events.append(event)

    # Combine events into a response
    conversation_id = None
    content = ""
    sql = None
    results = None

    for event in events:
        if event["type"] == "stream_start":
            conversation_id = event["conversation_id"]
        elif event["type"] == "stream_chunk":
            content += event["content"]
        elif event["type"] == "sql":
            sql = event["query"]
        elif event["type"] == "results":
            results = event

    return {
        "conversation_id": conversation_id,
        "content": content,
        "sql": sql,
        "results": results,
    }
