"""Checkpoint management 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 CheckpointSave(BaseModel):
    """Request body for saving a checkpoint label."""

    label: str = Field(..., description="User-friendly checkpoint label")
    description: str = Field(default="", description="Optional description")


class CheckpointInfo(BaseModel):
    """Checkpoint information response."""

    label: str
    checkpoint_id: str
    description: str
    created_at: str


class CheckpointRestore(BaseModel):
    """Request body for restoring a checkpoint."""

    label: str = Field(..., description="Checkpoint label to restore")


class CheckpointRestoreResult(BaseModel):
    """Restore result response."""

    success: bool
    label: str
    checkpoint_id: str | None = None
    message: str


@router.post("/{session_id}/checkpoints", response_model=CheckpointInfo)
async def save_checkpoint(
    session_id: str,
    body: CheckpointSave,
    request: Request,
    session_service: Any = Depends(get_session_service),
) -> CheckpointInfo:
    """Save a labeled checkpoint for the current session state."""
    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")

    from ieum.sessions import save_checkpoint_label

    cp_id = await save_checkpoint_label(session.thread_id, body.label, body.description)
    if cp_id is None:
        raise HTTPException(
            status_code=404,
            detail="No checkpoint found for current session. Send at least one message first.",
        )

    from datetime import UTC, datetime

    return CheckpointInfo(
        label=body.label,
        checkpoint_id=cp_id,
        description=body.description,
        created_at=datetime.now(UTC).isoformat(),
    )


@router.get("/{session_id}/checkpoints")
async def list_checkpoints(
    session_id: str,
    request: Request,
    session_service: Any = Depends(get_session_service),
) -> list[dict]:
    """List all labeled checkpoints 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")

    from ieum.sessions import list_checkpoint_labels

    return await list_checkpoint_labels(session.thread_id)


@router.post("/{session_id}/checkpoints/restore", response_model=CheckpointRestoreResult)
async def restore_checkpoint(
    session_id: str,
    body: CheckpointRestore,
    request: Request,
    session_service: Any = Depends(get_session_service),
) -> CheckpointRestoreResult:
    """Restore session to a labeled checkpoint."""
    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")

    from ieum.sessions import get_checkpoint_by_label

    cp_id = await get_checkpoint_by_label(session.thread_id, body.label)
    if not cp_id:
        raise HTTPException(
            status_code=404,
            detail=f"Checkpoint '{body.label}' not found.",
        )

    session._restore_checkpoint_id = cp_id
    return CheckpointRestoreResult(
        success=True,
        label=body.label,
        checkpoint_id=cp_id,
        message=f"Restored to checkpoint '{body.label}'. Next message will continue from this point.",
    )


@router.delete("/{session_id}/checkpoints/{label}")
async def delete_checkpoint(
    session_id: str,
    label: str,
    request: Request,
    session_service: Any = Depends(get_session_service),
) -> dict:
    """Delete a checkpoint label."""
    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")

    from ieum.sessions import delete_checkpoint_label

    deleted = await delete_checkpoint_label(session.thread_id, label)
    if not deleted:
        raise HTTPException(status_code=404, detail=f"Checkpoint '{label}' not found")

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