"""User profile API — /v1/users/*."""

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.tenant.context import resolve_request_context
from niannian.users.avatar import avatar_path, delete_avatar, has_avatar, save_avatar

if TYPE_CHECKING:
    from niannian.client import NianNian


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

    @router.get("/me/avatar")
    def get_my_avatar(request: Request) -> FileResponse:
        ctx = resolve_request_context(request, nn._config, home=nn._home)
        if not has_avatar(nn._home, ctx.user_id):
            raise HTTPException(status_code=404, detail={"code": "avatar_not_found", "message": "no avatar"})
        path = avatar_path(nn._home, ctx.user_id)
        return FileResponse(path, media_type="image/png")

    @router.put("/me/avatar")
    async def put_my_avatar(request: Request, file: UploadFile = File(...)) -> dict[str, Any]:
        ctx = resolve_request_context(request, nn._config, home=nn._home)
        data = await file.read()
        try:
            save_avatar(nn._home, ctx.user_id, data)
        except ValueError as exc:
            raise HTTPException(
                status_code=400,
                detail={"code": "invalid_avatar", "message": str(exc)},
            ) from exc
        except RuntimeError as exc:
            raise HTTPException(
                status_code=500,
                detail={"code": "avatar_unavailable", "message": str(exc)},
            ) from exc
        return {"ok": True, "has_avatar": True, "user_id": ctx.user_id}

    @router.delete("/me/avatar")
    def delete_my_avatar(request: Request) -> dict[str, Any]:
        ctx = resolve_request_context(request, nn._config, home=nn._home)
        delete_avatar(nn._home, ctx.user_id)
        return {"ok": True, "has_avatar": False, "user_id": ctx.user_id}

    return router
