from __future__ import annotations

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

from app.connectors.config_backup import list_backups, prepare_backup_manifest
from app.connectors.gitea_repo_sync import list_activity, run_gitea_repo_sync
from app.connectors.ops_maintenance import list_notes, run_maintenance_scan
from app.connectors.proxmox import get_status_summary, get_topology, poll_and_snapshot

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


class BackupRunBody(BaseModel):
    approval_request_id: int | None = None


class GiteaSyncBody(BaseModel):
    reason: str = Field(default="manual", max_length=120)


@router.get("/status")
def ops_status() -> dict:
    try:
        return get_status_summary()
    except Exception as exc:  # noqa: BLE001
        raise HTTPException(status_code=500, detail=f"ops status failed: {exc}") from exc


@router.get("/topology")
def ops_topology() -> dict:
    try:
        return get_topology()
    except Exception as exc:  # noqa: BLE001
        raise HTTPException(status_code=500, detail=f"ops topology failed: {exc}") from exc


@router.post("/refresh")
def ops_refresh() -> dict:
    try:
        return poll_and_snapshot()
    except Exception as exc:  # noqa: BLE001
        raise HTTPException(status_code=500, detail=f"ops refresh failed: {exc}") from exc


@router.get("/backups")
def ops_backups(limit: int = 10) -> dict:
    return {"items": list_backups(limit), "manifest": prepare_backup_manifest()}


@router.post("/backup/run")
def ops_backup_run(body: BackupRunBody) -> dict:
    try:
        return run_gitea_repo_sync(reason="approved_backup", approval_request_id=body.approval_request_id)
    except Exception as exc:  # noqa: BLE001
        raise HTTPException(status_code=500, detail=str(exc)) from exc


@router.post("/gitea/sync")
def ops_gitea_sync(body: GiteaSyncBody) -> dict:
    try:
        return run_gitea_repo_sync(reason=body.reason)
    except Exception as exc:  # noqa: BLE001
        raise HTTPException(status_code=500, detail=str(exc)) from exc


@router.get("/sysops-activity")
def ops_sysops_activity(limit: int = 30) -> dict:
    return {"items": list_activity(limit), "count": len(list_activity(limit))}


@router.get("/maintenance")
def ops_maintenance(limit: int = 15) -> dict:
    return {"items": list_notes(limit, unresolved_only=True)}


@router.post("/maintenance/scan")
def ops_maintenance_scan() -> dict:
    try:
        return run_maintenance_scan()
    except Exception as exc:  # noqa: BLE001
        raise HTTPException(status_code=500, detail=str(exc)) from exc
