"""Chat attachment API — /v1/chat/attachments/*."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from fastapi import APIRouter, File, HTTPException, Request, UploadFile
from fastapi.responses import FileResponse

from niannian.chat.attachments import (
    get_attachment_blob_path,
    get_attachment_meta,
    save_attachment,
    soft_delete_attachment,
    validate_attachment_id,
)
from niannian.tenant.context import resolve_request_context

if TYPE_CHECKING:
    from niannian.client import NianNian


def create_chat_attachments_router(nn: NianNian) -> APIRouter:
    router = APIRouter(prefix="/v1/chat", tags=["chat"])

    @router.post("/attachments")
    async def post_attachment(request: Request, file: UploadFile = File(...)) -> dict[str, Any]:
        ctx = resolve_request_context(request, nn._config, home=nn._home)
        data = await file.read()
        try:
            result = save_attachment(
                nn._home,
                ctx.user_id,
                data,
                mime=file.content_type,
                filename=file.filename,
            )
        except ValueError as exc:
            raise HTTPException(
                status_code=400,
                detail={"code": "invalid_attachment", "message": str(exc)},
            ) from exc
        return result

    @router.get("/attachments/{attachment_id}")
    def get_attachment(request: Request, attachment_id: str) -> FileResponse:
        ctx = resolve_request_context(request, nn._config, home=nn._home)
        try:
            aid = validate_attachment_id(attachment_id)
        except ValueError as exc:
            raise HTTPException(
                status_code=400,
                detail={"code": "invalid_attachment_id", "message": str(exc)},
            ) from exc

        meta = get_attachment_meta(nn._home, ctx.user_id, aid)
        if meta is None:
            raise HTTPException(status_code=404, detail={"code": "attachment_not_found"})
        path = get_attachment_blob_path(nn._home, ctx.user_id, aid)
        if path is None:
            raise HTTPException(status_code=404, detail={"code": "attachment_not_found"})
        return FileResponse(path, media_type=str(meta.get("mime") or "application/octet-stream"))

    @router.delete("/attachments/{attachment_id}")
    def delete_attachment(request: Request, attachment_id: str) -> dict[str, Any]:
        ctx = resolve_request_context(request, nn._config, home=nn._home)
        try:
            aid = validate_attachment_id(attachment_id)
        except ValueError as exc:
            raise HTTPException(
                status_code=400,
                detail={"code": "invalid_attachment_id", "message": str(exc)},
            ) from exc

        if not soft_delete_attachment(nn._home, ctx.user_id, aid):
            raise HTTPException(status_code=404, detail={"code": "attachment_not_found"})
        return {"ok": True, "attachment_id": aid, "deleted": True}

    return router
