"""FastAPI router for the lightweight Memory System API."""
from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, Query, status

from .auth import verify_api_key
from .schemas import (
    MemoryWriteRequest,
    MessageIngestRequest,
    ProfileRequest,
    ResourceUploadRequest,
    SearchRequest,
    SessionContextRequest,
    SessionUserRequest,
    TaskStatusRequest,
    UserCreateRequest,
)
from .service import MemorySystemService


router = APIRouter(
    prefix="/memory-system",
    tags=["memory-system"],
    dependencies=[Depends(verify_api_key)],
)


def get_service() -> MemorySystemService:
    return MemorySystemService()


def user_auth_error(exc: PermissionError) -> HTTPException:
    return HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(exc))


@router.get("/health")
async def health(service: MemorySystemService = Depends(get_service)):
    return await service.health()


@router.post("/users")
async def create_user(request: UserCreateRequest, service: MemorySystemService = Depends(get_service)):
    return await service.create_user(request.user_id)


@router.post("/messages")
async def ingest_messages(
    request: MessageIngestRequest,
    service: MemorySystemService = Depends(get_service),
):
    try:
        return await service.ingest_messages(request)
    except ValueError as exc:
        raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc
    except PermissionError as exc:
        raise user_auth_error(exc) from exc


@router.post("/resources")
async def upload_resource(
    request: ResourceUploadRequest,
    service: MemorySystemService = Depends(get_service),
):
    try:
        return await service.upload_resource(request)
    except PermissionError as exc:
        raise user_auth_error(exc) from exc


@router.delete("/resources")
async def delete_resource(
    user_id: str = Query(min_length=1),
    user_key: str = Query(min_length=1),
    uri: str = Query(min_length=1),
    recursive: bool = Query(default=True),
    service: MemorySystemService = Depends(get_service),
):
    try:
        return await service.delete_resource(user_id, user_key, uri, recursive=recursive)
    except PermissionError as exc:
        raise user_auth_error(exc) from exc


@router.get("/memories")
async def list_memories(
    user_id: str = Query(min_length=1),
    user_key: str = Query(min_length=1),
    uri: str = Query(default="viking://user/memories", min_length=1),
    recursive: bool = Query(default=True),
    service: MemorySystemService = Depends(get_service),
):
    try:
        return await service.list_memories(user_id, user_key, uri=uri, recursive=recursive)
    except PermissionError as exc:
        raise user_auth_error(exc) from exc


@router.get("/memories/content")
async def read_memory(
    user_id: str = Query(min_length=1),
    user_key: str = Query(min_length=1),
    uri: str = Query(min_length=1),
    service: MemorySystemService = Depends(get_service),
):
    try:
        return await service.read_memory(user_id, user_key, uri)
    except PermissionError as exc:
        raise user_auth_error(exc) from exc


@router.post("/memories")
async def write_memory(
    request: MemoryWriteRequest,
    service: MemorySystemService = Depends(get_service),
):
    try:
        return await service.write_memory(request)
    except PermissionError as exc:
        raise user_auth_error(exc) from exc


@router.delete("/memories")
async def delete_memory(
    user_id: str = Query(min_length=1),
    user_key: str = Query(min_length=1),
    uri: str = Query(min_length=1),
    recursive: bool = Query(default=False),
    service: MemorySystemService = Depends(get_service),
):
    try:
        return await service.delete_memory(user_id, user_key, uri, recursive=recursive)
    except PermissionError as exc:
        raise user_auth_error(exc) from exc


@router.post("/sessions/{session_id}/commit")
async def commit_session(
    session_id: str,
    request: SessionUserRequest,
    service: MemorySystemService = Depends(get_service),
):
    try:
        return await service.commit_session(request.user_id, request.user_key, session_id)
    except PermissionError as exc:
        raise user_auth_error(exc) from exc


@router.post("/sessions/{session_id}/extract")
async def extract_session(
    session_id: str,
    request: SessionUserRequest,
    service: MemorySystemService = Depends(get_service),
):
    try:
        return await service.extract_session(request.user_id, request.user_key, session_id)
    except PermissionError as exc:
        raise user_auth_error(exc) from exc


@router.post("/sessions/{session_id}/context")
async def get_session_context(
    session_id: str,
    request: SessionContextRequest,
    service: MemorySystemService = Depends(get_service),
):
    try:
        return await service.get_session_context(session_id, request)
    except PermissionError as exc:
        raise user_auth_error(exc) from exc


@router.get("/sessions/{session_id}/context")
async def get_session_context_from_query(
    session_id: str,
    user_id: str = Query(min_length=1),
    user_key: str = Query(min_length=1),
    query: str = Query(min_length=1),
    limit: int = Query(default=10, ge=1, le=100),
    service: MemorySystemService = Depends(get_service),
):
    try:
        request = SessionContextRequest(user_id=user_id, user_key=user_key, query=query, limit=limit)
        return await service.get_session_context(session_id, request)
    except PermissionError as exc:
        raise user_auth_error(exc) from exc


@router.get("/openviking/tasks/{task_id}")
async def get_openviking_task(
    task_id: str,
    user_id: str = Query(min_length=1),
    user_key: str = Query(min_length=1),
    session_id: str | None = Query(default=None, min_length=1),
    service: MemorySystemService = Depends(get_service),
):
    try:
        return await service.get_openviking_task(
            user_id,
            user_key,
            task_id,
            session_id=session_id,
        )
    except PermissionError as exc:
        raise user_auth_error(exc) from exc


@router.post("/openviking/tasks/{task_id}")
async def get_openviking_task_from_body(
    task_id: str,
    request: TaskStatusRequest,
    service: MemorySystemService = Depends(get_service),
):
    try:
        return await service.get_openviking_task(
            request.user_id,
            request.user_key,
            task_id,
            session_id=request.session_id,
        )
    except PermissionError as exc:
        raise user_auth_error(exc) from exc


@router.post("/search")
async def search(
    request: SearchRequest,
    service: MemorySystemService = Depends(get_service),
):
    try:
        return await service.search(request)
    except PermissionError as exc:
        raise user_auth_error(exc) from exc


@router.post("/users/{user_id}/profile")
async def get_profile_from_body(
    user_id: str,
    request: ProfileRequest,
    service: MemorySystemService = Depends(get_service),
):
    try:
        return await service.get_profile(
            user_id,
            request.user_key,
            query=request.query,
            limit=request.limit,
            level=request.level,
        )
    except PermissionError as exc:
        raise user_auth_error(exc) from exc


@router.get("/users/{user_id}/profile")
async def get_profile(
    user_id: str,
    user_key: str = Query(min_length=1),
    query: str = Query(default="用户画像", min_length=1),
    limit: int = Query(default=10, ge=1, le=100),
    level: int = Query(default=2, ge=0),
    service: MemorySystemService = Depends(get_service),
):
    try:
        return await service.get_profile(user_id, user_key, query=query, limit=limit, level=level)
    except PermissionError as exc:
        raise user_auth_error(exc) from exc
