"""Error log API — query and manage persistent error logs."""

from __future__ import annotations

import logging

from fastapi import APIRouter, HTTPException, Query, Request

log = logging.getLogger(__name__)

router = APIRouter(prefix="/logs", tags=["logs"])


def _get_logger(request: Request):
    el = getattr(request.app.state, "error_logger", None)
    if not el:
        raise HTTPException(status_code=503, detail="Error logger not initialized")
    return el


@router.get("")
async def get_errors(
    request: Request,
    limit: int = Query(100, ge=1, le=1000),
    offset: int = Query(0, ge=0),
    level: str = Query("", description="Filter by level: ERROR, WARNING, CRITICAL"),
    source: str = Query("", description="Filter by source (partial match)"),
    resolved: bool | None = Query(None, description="Filter by resolved status"),
    since: str = Query("", description="ISO timestamp — only errors after this time"),
) -> dict:
    """List error logs with filtering and pagination."""
    el = _get_logger(request)
    errors = await el.get_errors(
        limit=limit, offset=offset, level=level,
        source=source, resolved=resolved, since=since,
    )
    return {"errors": errors, "count": len(errors), "offset": offset, "limit": limit}


@router.get("/stats")
async def get_stats(request: Request) -> dict:
    """Error log summary statistics."""
    el = _get_logger(request)
    return await el.get_stats()


@router.get("/{error_id}")
async def get_error(request: Request, error_id: int) -> dict:
    """Get a single error log entry with full traceback."""
    el = _get_logger(request)
    entry = await el.get_error(error_id)
    if not entry:
        raise HTTPException(status_code=404, detail="Error not found")
    return entry


@router.post("/{error_id}/resolve")
async def resolve_error(request: Request, error_id: int) -> dict:
    """Mark an error as resolved."""
    el = _get_logger(request)
    ok = await el.resolve_error(error_id)
    if not ok:
        raise HTTPException(status_code=404, detail="Error not found")
    return {"status": "resolved", "id": error_id}


@router.post("/resolve-all")
async def resolve_all(request: Request) -> dict:
    """Mark all unresolved errors as resolved."""
    el = _get_logger(request)
    count = await el.resolve_all()
    return {"status": "resolved", "count": count}


@router.delete("/cleanup")
async def cleanup(request: Request, older_than_days: int = Query(30, ge=1)) -> dict:
    """Delete resolved errors older than N days."""
    el = _get_logger(request)
    count = await el.delete_old(older_than_days)
    return {"status": "cleaned", "deleted": count}
