from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse
from starlette import status

from .common import (
    CurrentUser,
    ServicesDep,
    _build_epicrisis_document_bundle,
    _build_full_epicrisis_context,
    logger,
)


router = APIRouter()


@router.get("/paciente/epicrisis", response_class=HTMLResponse)
async def epicrisis_patient_view(
    request: Request,
    nombre_paciente: str = "BLANCA LIEJA",
    *,
    current_user: CurrentUser,
    services: ServicesDep,
):
    """Renderiza la vista de epicrisis combinando historia clínica y documento quirúrgico del paciente."""
    templates = services.templates
    mongo = services.mongo_analyses
    try:
        bundle = _build_epicrisis_document_bundle(
            mongo,
            current_user.username,
            nombre_paciente,
        )
        contexto = _build_full_epicrisis_context(
            services=services,
            bundle=bundle,
            username=current_user.username,
            cie10_retriever=services.cie10_retriever,
            regen_url=None,
            regen_case_key="",
            epicrisis_cached=False,
            request=request,
            current_user=current_user,
        )
        return templates.TemplateResponse(request, "epicrisis.html", contexto)
    except Exception:
        logger.exception("Error en epicrisis_patient_view")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Error al cargar la epicrisis"
        )

