"""
Admin endpoints for SLTK API.

Handles job management, cleanup, and administrative functions.
"""

from __future__ import annotations

import asyncio
import logging

from fastapi import APIRouter

from sltk.api.routers.extraction import (
    JOB_CLEANUP_INTERVAL_SECONDS,
    JOB_TTL_HOURS,
    MAX_JOBS,
    _jobs_lock,
    cleanup_old_jobs,
    get_job_stats,
    jobs,
)

router = APIRouter(prefix="/api/admin", tags=["admin"])
logger = logging.getLogger(__name__)


@router.post("/cleanup-jobs")
async def trigger_job_cleanup():
    """
    Manually trigger job cleanup.

    This endpoint removes:
    - Completed/failed/cancelled jobs older than JOB_TTL_HOURS (default: 24 hours)
    - Excess jobs when the total exceeds MAX_JOBS (default: 1000)

    Returns:
        JSON with number of jobs removed and remaining job count.
    """
    removed = cleanup_old_jobs()
    with _jobs_lock:
        remaining = len(jobs)
    return {
        "removed": removed,
        "remaining": remaining,
        "ttl_hours": JOB_TTL_HOURS,
        "max_jobs": MAX_JOBS,
    }


@router.get("/job-stats")
async def get_job_stats_endpoint():
    """
    Get statistics about current job storage.

    Returns:
        JSON with job counts by status, total log entries, and configuration.
    """
    return get_job_stats()


# ============================================================================
# Job Cleanup Task (started from main.py)
# ============================================================================


async def periodic_cleanup():
    """Periodically clean up old jobs to prevent unbounded memory growth."""
    while True:
        await asyncio.sleep(JOB_CLEANUP_INTERVAL_SECONDS)
        try:
            removed = cleanup_old_jobs()
            if removed > 0:
                logger.info(f"Cleaned up {removed} old jobs")
        except Exception as e:
            logger.error(f"Job cleanup failed: {e}")
