import json
import uuid

from fastapi import APIRouter, Depends, Header, HTTPException, Response
from sqlalchemy import text

from app.api.auth_routes import require_permission
from app.core.db import db_session
from app.services.auth_service import audit, check_csrf
from app.services.operations_service import operations_overview, readiness, run_operational_checks


health_router = APIRouter(prefix="/health", tags=["health"])
admin_router = APIRouter(prefix="/panel/admin/operations", tags=["operations"])


@health_router.get("/ready")
def ready(response: Response):
    ok, detail = readiness()
    if not ok:
        response.status_code = 503
    return {"ok": ok, "service": "documenta-api", **detail}


@admin_router.get("")
def overview(user=Depends(require_permission("operacion.monitoreo"))):
    return operations_overview()


@admin_router.post("/run", status_code=201)
def run_checks(x_csrf_token: str | None = Header(default=None),
               user=Depends(require_permission("operacion.monitoreo"))):
    try:
        check_csrf(user, x_csrf_token)
    except ValueError as exc:
        raise HTTPException(403, str(exc)) from exc
    result = run_operational_checks(user["usuario_id"])
    with db_session() as db:
        audit(db, user["usuario_id"], "CONTROLES_OPERACION_EJECUTADOS", "OPERACION", None,
              f"{result['estado']}: {result['resumen']}")
    return result


@admin_router.get("/runs/{run_uuid}")
def run_detail(run_uuid: str, user=Depends(require_permission("operacion.monitoreo"))):
    try:
        binary_uuid = uuid.UUID(run_uuid).bytes
    except ValueError as exc:
        raise HTTPException(404, "Ejecución no encontrada") from exc
    with db_session() as db:
        run = db.execute(text("""
          SELECT tipo,version_aplicacion,estado,resumen,controles_total,controles_ok,
                 controles_advertencia,controles_error,iniciada_en,finalizada_en
          FROM operacion_ejecuciones WHERE uuid=:uuid
        """), {"uuid": binary_uuid}).mappings().first()
        if not run:
            raise HTTPException(404, "Ejecución no encontrada")
        rows = db.execute(text("""
          SELECT codigo,categoria,componente,estado,duracion_ms,detalle,evidencia_json,creado_en
          FROM operacion_controles
          WHERE ejecucion_id=(SELECT id FROM operacion_ejecuciones WHERE uuid=:uuid)
          ORDER BY id
        """), {"uuid": binary_uuid}).mappings().all()
    controls = []
    for source in rows:
        item = dict(source)
        item["evidencia"] = json.loads(item.pop("evidencia_json") or "null")
        controls.append(item)
    return {"ejecucion": dict(run), "controles": controls}
