from typing import Final
from urllib.parse import quote

from bson import ObjectId
from fastapi import APIRouter, Query, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from starlette import status

from .common import ServicesDep


router = APIRouter()

CASE_DETAIL_PATH: Final[str] = "/casos"
DASHBOARD_PATH: Final[str] = "/dashboard"
LOGIN_TEMPLATE: Final[str] = "login.html"


@router.get("/", response_class=HTMLResponse)
async def login_form(request: Request, services: ServicesDep):
    templates = services.templates
    return templates.TemplateResponse(request, LOGIN_TEMPLATE, {"request": request})


@router.get("/consulta", response_class=HTMLResponse)
async def consulta(request: Request, services: ServicesDep):
    return RedirectResponse(url=DASHBOARD_PATH, status_code=status.HTTP_307_TEMPORARY_REDIRECT)


@router.get("/subir_documento", response_class=HTMLResponse)
async def subir_documento_form(request: Request, services: ServicesDep):
    destination = CASE_DETAIL_PATH
    if request.url.query:
        destination = f"{destination}?{request.url.query}"
    return RedirectResponse(url=destination, status_code=status.HTTP_307_TEMPORARY_REDIRECT)


@router.get("/ver_historia", response_class=HTMLResponse)
async def ver_historia(
    request: Request,
    services: ServicesDep,
    id: str | None = Query(default=None, deprecated=True),
    case_key: str | None = Query(default=None),
    documento_id: str | None = Query(default=None),
):
    normalized_case_key = str(case_key or "").strip()
    normalized_documento_id = str(documento_id or id or "").strip()

    if normalized_case_key:
        destination = f"{CASE_DETAIL_PATH}?case_key={quote(normalized_case_key)}"
        if normalized_documento_id:
            destination = f"{destination}&documento_id={quote(normalized_documento_id)}"
        return RedirectResponse(url=destination, status_code=status.HTTP_307_TEMPORARY_REDIRECT)

    if normalized_documento_id and ObjectId.is_valid(normalized_documento_id):
        document = services.mongo_analyses.collection.find_one({"_id": ObjectId(normalized_documento_id)})
        resolved_case_key = str((document or {}).get("case_key") or "").strip()
        if resolved_case_key:
            destination = f"{CASE_DETAIL_PATH}?case_key={quote(resolved_case_key)}&documento_id={quote(normalized_documento_id)}"
            return RedirectResponse(url=destination, status_code=status.HTTP_307_TEMPORARY_REDIRECT)

    return RedirectResponse(url=CASE_DETAIL_PATH, status_code=status.HTTP_307_TEMPORARY_REDIRECT)


@router.get("/pacientes", response_class=HTMLResponse)
async def ver_pacientes(request: Request, services: ServicesDep):
    destination = CASE_DETAIL_PATH
    if request.url.query:
        destination = f"{destination}?{request.url.query}"
    return RedirectResponse(url=destination, status_code=status.HTTP_307_TEMPORARY_REDIRECT)
