import uuid
from datetime import datetime
from typing import Optional

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.dependencies import DBSessionDep, CitizenDep
from app.domain.models import (
    ThreadCreateRequest, ThreadCreatedResponse,
    MessageCreateRequest, MessageListResponse, SenderRole,
)
from app.service import threads_service

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

@router.post(
    "/documents/{document_id}/threads",
    response_model=ThreadCreatedResponse,
    status_code=status.HTTP_201_CREATED,
)
async def create_thread_for_document(
    document_id: str,
    payload: ThreadCreateRequest,
    session: AsyncSession = DBSessionDep,
    citizen = CitizenDep,
):
    try:
        doc_uuid = uuid.UUID(document_id)
    except ValueError:
        raise HTTPException(status_code=404, detail="Document not found")

    return await threads_service.create_thread(
        document_id=doc_uuid,
        req=payload,
        session=session,
        citizen_id=citizen.sub,
    )

@router.get(
    "/threads/{thread_id}/messages",
    response_model=MessageListResponse,
)
async def get_thread_messages(
    thread_id: str,
    limit: int = Query(20, ge=1, le=100),
    before: Optional[datetime] = Query(None),
    session: AsyncSession = DBSessionDep,
    user = CitizenDep,
):
    try:
        thread_uuid = uuid.UUID(thread_id)
    except ValueError:
        raise HTTPException(status_code=404, detail="Thread not found")

    return await threads_service.list_messages(
        thread_id=thread_uuid,
        session=session,
        limit=limit,
        before=before,
    )

@router.post(
    "/threads/{thread_id}/messages",
    response_model=MessageListResponse.__fields__["data"].annotation.__args__[0],
    status_code=status.HTTP_201_CREATED,
)
async def post_thread_message(
    thread_id: str,
    payload: MessageCreateRequest,
    session: AsyncSession = DBSessionDep,
    user = CitizenDep,
):
    try:
        thread_uuid = uuid.UUID(thread_id)
    except ValueError:
        raise HTTPException(status_code=404, detail="Thread not found")

    msg = await threads_service.add_message(
        thread_id=thread_uuid,
        req=payload,
        session=session,
        sender_role=SenderRole.CITIZEN,
    )
    return msg
