"""
Archive API Routes for CodeContext server.

Handles viewing, restoring, and permanently deleting archived (soft-deleted) memories.
"""

from fastapi import APIRouter, Query, HTTPException

from ..services.store_manager import get_store, list_projects, ALL_PROJECTS


router = APIRouter()


@router.get("/api/archive")
async def get_archived_memories(
    project: str = Query(...),
    limit: int = Query(default=50),
    offset: int = Query(default=0),
    reason: str = Query(default="")
):
    """
    Get archived (deleted) memories.

    Args:
        project: Project name
        limit: Max entries to return
        offset: Number of entries to skip
        reason: Filter by deletion_reason (e.g., "conflict_resolution", "consolidation")
    """
    store = get_store(project)
    reason_filter = reason if reason else None
    memories = store.list_archived(limit=limit, offset=offset, reason_filter=reason_filter)
    stats = store.get_archive_stats()
    return {
        "project": project,
        "memories": memories,
        "stats": stats,
        "has_more": len(memories) == limit
    }


@router.get("/api/archive/stats")
async def get_archive_stats_endpoint(project: str = Query(...)):
    """Get archive statistics for a project."""
    store = get_store(project)
    stats = store.get_archive_stats()
    return {"project": project, **stats}


@router.post("/api/archive/{memory_id}/restore")
async def restore_archived_memory(
    memory_id: str,
    project: str = Query(...)
):
    """
    Restore an archived memory back to the main table.

    Creates a new memory with _restored_ suffix in ID.
    """
    store = get_store(project)
    result = store.restore_memory(memory_id)
    return {"project": project, **result}


@router.delete("/api/archive/{memory_id}")
async def permanently_delete_archived(
    memory_id: str,
    project: str = Query(...)
):
    """
    Permanently delete an archived memory (no recovery).

    Use with caution - this action cannot be undone.
    """
    store = get_store(project)
    success = store.permanently_delete_archived(memory_id)
    if not success:
        raise HTTPException(status_code=404, detail="Archived memory not found")
    return {"project": project, "memory_id": memory_id, "permanently_deleted": True}


@router.get("/api/pending-conflicts-count")
async def get_pending_conflicts_count(project: str = Query(...)):
    """Get the count of pending conflicts (for badge updates)."""
    if project == ALL_PROJECTS:
        # Sum counts across all projects
        projects = list_projects()
        total_count = sum(get_store(p).count_pending_conflicts() for p in projects)
        return {"project": project, "count": total_count}
    else:
        store = get_store(project)
        return {"project": project, "count": store.count_pending_conflicts()}
