"""Cron API — manage persistent scheduled jobs."""

from __future__ import annotations

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

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


class CronJobRequest(BaseModel):
    name: str
    schedule: str  # cron expression or 'every 15m'
    action: str
    action_args: dict | None = None
    deliver_to: str = "observations"


@router.get("/jobs")
async def list_jobs(request: Request) -> list[dict]:
    """List all cron jobs."""
    return await request.app.state.cron.list_jobs()


@router.post("/jobs")
async def add_job(request: Request, body: CronJobRequest) -> dict:
    """Add or update a cron job."""
    cron = request.app.state.cron
    return await cron.add_job(
        name=body.name,
        schedule=body.schedule,
        action=body.action,
        action_args=body.action_args,
        deliver_to=body.deliver_to,
    )


@router.delete("/jobs/{name}")
async def remove_job(request: Request, name: str) -> dict:
    """Remove a cron job."""
    cron = request.app.state.cron
    removed = await cron.remove_job(name)
    if not removed:
        raise HTTPException(status_code=404, detail=f"Job not found: {name}")
    return {"removed": name}


@router.post("/jobs/{name}/enable")
async def enable_job(request: Request, name: str) -> dict:
    """Enable a cron job."""
    await request.app.state.cron.enable_job(name, enabled=True)
    return {"name": name, "enabled": True}


@router.post("/jobs/{name}/disable")
async def disable_job(request: Request, name: str) -> dict:
    """Disable a cron job."""
    await request.app.state.cron.enable_job(name, enabled=False)
    return {"name": name, "enabled": False}


@router.get("/history")
async def get_history(request: Request, job_name: str | None = None, limit: int = 20) -> list[dict]:
    """Get cron execution history."""
    return await request.app.state.cron.get_history(job_name=job_name, limit=limit)


@router.post("/run")
async def run_now(request: Request) -> dict:
    """Manually trigger a cron check cycle."""
    executed = await request.app.state.cron.check_and_run()
    return {"executed": executed}
