# #region health_router [C:3] [TYPE Module] [SEMANTICS fastapi, health, api, search, dashboard]
# @BRIEF API endpoints for dashboard health monitoring and status aggregation.
# @LAYER UI
# @RELATION DEPENDS_ON -> [health_service]


from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session

from ...core.database import get_db
from ...dependencies import get_config_manager, get_task_manager, has_permission
from ...schemas.health import HealthSummaryResponse
from ...services.health_service import HealthService

router = APIRouter(prefix="/api/health", tags=["Health"])

# #region get_health_summary [TYPE Function]
# @BRIEF Get aggregated health status for all dashboards.
# @PRE  Caller has read permission for dashboard health view.
# @POST  Returns HealthSummaryResponse.
# @RELATION CALLS -> [HealthService]
@router.get("/summary", response_model=HealthSummaryResponse)
async def get_health_summary(
    environment_id: str | None = Query(None),
    db: Session = Depends(get_db),
    config_manager = Depends(get_config_manager),
    _ = Depends(has_permission("plugin:migration", "READ"))
):
    """
    @PURPOSE: Get aggregated health status for all dashboards.
    @POST: Returns HealthSummaryResponse
    """
    if not config_manager.get_config().settings.features.health_monitor:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Health monitor feature is disabled")
    service = HealthService(db, config_manager=config_manager)
    return await service.get_health_summary(environment_id=environment_id)
# #endregion get_health_summary


# #region delete_health_report [TYPE Function]
# @BRIEF Delete one persisted dashboard validation report from health summary.
# @PRE  Caller has write permission for tasks/report maintenance.
# @POST  Validation record is removed; linked task/logs are cleaned when available.
# @RELATION CALLS -> [HealthService]
@router.delete("/summary/{record_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_health_report(
    record_id: str,
    db: Session = Depends(get_db),
    config_manager = Depends(get_config_manager),
    task_manager = Depends(get_task_manager),
    _ = Depends(has_permission("tasks", "WRITE")),
):
    """
    @PURPOSE: Delete a persisted dashboard validation report from health summary.
    @POST: Validation record is removed; linked task/logs are deleted when present.
    """
    if not config_manager.get_config().settings.features.health_monitor:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Health monitor feature is disabled")
    service = HealthService(db, config_manager=config_manager)
    if not service.delete_validation_report(record_id, task_manager=task_manager):
        raise HTTPException(status_code=404, detail="Health report not found")
    return
# #endregion delete_health_report

# #endregion health_router
