"""Cross-session memory API routes."""

import logging
from typing import Any

from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel, Field

from ieum.server.auth import get_request_user_id

logger = logging.getLogger(__name__)

router = APIRouter()


def get_session_service(request: Request) -> Any:
    """Dependency to get the session service."""
    return request.app.state.session_service


class MemoryEntry(BaseModel):
    """Memory entry response."""

    key: str
    preview: str
    created_at: str | None = None
    modified_at: str | None = None


class MemoryDetail(BaseModel):
    """Full memory entry with content."""

    key: str
    content: str
    created_at: str | None = None
    modified_at: str | None = None


class MemoryWrite(BaseModel):
    """Request body for writing a memory entry."""

    key: str = Field(..., description="Memory key/identifier")
    content: str = Field(..., description="Memory content")


class MemoryClearResult(BaseModel):
    """Result of clearing all memories."""

    cleared: int


@router.get("/{session_id}/memory")
async def list_memories(
    session_id: str,
    request: Request,
    session_service: Any = Depends(get_session_service),
) -> list[dict]:
    """List all memory entries for a session."""
    user_id = get_request_user_id(request)
    session = session_service.get_session(session_id, user_id=user_id)
    if session is None:
        raise HTTPException(status_code=404, detail="Session not found")

    if session.store is None:
        return []

    from ieum.auto_memory import list_memories as _list_memories

    return await _list_memories(session.store)


@router.get("/{session_id}/memory/{key}", response_model=MemoryDetail)
async def get_memory(
    session_id: str,
    key: str,
    request: Request,
    session_service: Any = Depends(get_session_service),
) -> MemoryDetail:
    """Get a specific memory entry by key."""
    user_id = get_request_user_id(request)
    session = session_service.get_session(session_id, user_id=user_id)
    if session is None:
        raise HTTPException(status_code=404, detail="Session not found")

    if session.store is None:
        raise HTTPException(status_code=404, detail="Memory store not available")

    from ieum.auto_memory import read_memory

    content = await read_memory(session.store, key)
    if content is None:
        raise HTTPException(status_code=404, detail=f"Memory '{key}' not found")

    return MemoryDetail(key=key, content=content)


@router.put("/{session_id}/memory", response_model=MemoryDetail)
async def write_memory(
    session_id: str,
    body: MemoryWrite,
    request: Request,
    session_service: Any = Depends(get_session_service),
) -> MemoryDetail:
    """Write or update a memory entry."""
    user_id = get_request_user_id(request)
    session = session_service.get_session(session_id, user_id=user_id)
    if session is None:
        raise HTTPException(status_code=404, detail="Session not found")

    if session.store is None:
        raise HTTPException(status_code=400, detail="Memory store not available")

    from ieum.auto_memory import write_memory as _write_memory

    await _write_memory(session.store, body.key, body.content)
    return MemoryDetail(key=body.key, content=body.content)


@router.delete("/{session_id}/memory/{key}")
async def delete_memory(
    session_id: str,
    key: str,
    request: Request,
    session_service: Any = Depends(get_session_service),
) -> dict:
    """Delete a memory entry."""
    user_id = get_request_user_id(request)
    session = session_service.get_session(session_id, user_id=user_id)
    if session is None:
        raise HTTPException(status_code=404, detail="Session not found")

    if session.store is None:
        raise HTTPException(status_code=400, detail="Memory store not available")

    from ieum.auto_memory import delete_memory as _delete_memory

    deleted = await _delete_memory(session.store, key)
    if not deleted:
        raise HTTPException(status_code=404, detail=f"Memory '{key}' not found")

    return {"key": key, "deleted": True}


@router.delete("/{session_id}/memory", response_model=MemoryClearResult)
async def clear_memories(
    session_id: str,
    request: Request,
    session_service: Any = Depends(get_session_service),
) -> MemoryClearResult:
    """Clear all memory entries."""
    user_id = get_request_user_id(request)
    session = session_service.get_session(session_id, user_id=user_id)
    if session is None:
        raise HTTPException(status_code=404, detail="Session not found")

    if session.store is None:
        return MemoryClearResult(cleared=0)

    from ieum.auto_memory import clear_memories as _clear_memories

    count = await _clear_memories(session.store)
    return MemoryClearResult(cleared=count)
