from typing import Any, List, Dict from fastapi import APIRouter, Depends from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from datetime import datetime, timedelta import time from core.deps import get_db, get_current_staff_user, get_current_super_admin, get_arq_pool from core.config import get_settings from models.ai_workflow import AIWorkflow from models.ai_interaction import AIInteraction from models.meta_infra_health import MetaInfraHealth from schemas.system import AIWorkflowRead, AIInteractionRead, MetaInfraHealthRead from arq.connections import ArqRedis router = APIRouter() settings = get_settings() from core.observability import check_infra_health @router.get("/status/", dependencies=[Depends(get_current_super_admin)]) async def get_system_status( db: AsyncSession = Depends(get_db), arq_pool: ArqRedis = Depends(get_arq_pool) ) -> Dict[str, Any]: """ Aggregates real-time health metrics for the core infrastructure nodes. Calculates latency on-demand for accurate dashboard reporting. """ # Use the unified health helper for DB and Redis infra_health = await check_infra_health(db, arq_pool) results = { "database": { "status": infra_health["database"], "latency_ms": infra_health.get("database_latency", 0.0) }, "redis": { "status": infra_health["redis"], "latency_ms": infra_health.get("redis_latency", 0.0), "pending_jobs": infra_health.get("pending_jobs", 0) }, "ollama": {"status": "DOWN", "latency_ms": 0.0}, "timestamp": datetime.utcnow() } # 3. Ollama Check start_time = time.perf_counter() try: import httpx async with httpx.AsyncClient(timeout=2.0) as client: resp = await client.get(f"{settings.OLLAMA_BASE_URL}/api/tags") if resp.status_code == 200: results["ollama"]["status"] = "UP" results["ollama"]["latency_ms"] = round((time.perf_counter() - start_time) * 1000, 2) except Exception: results["ollama"]["status"] = "DOWN" return results from uuid import UUID from typing import Any, Dict, Optional @router.get("/workflows/", response_model=List[AIWorkflowRead], dependencies=[Depends(get_current_staff_user)]) async def get_recent_workflows( db: AsyncSession = Depends(get_db), ticket_id: Optional[UUID] = None, offset: int = 0, limit: int = 20 ) -> List[AIWorkflow]: """ Retrieves AI workflows with optional ticket filtering and pagination. """ stmt = select(AIWorkflow) if ticket_id: stmt = stmt.where(AIWorkflow.entity_id == ticket_id) stmt = stmt.order_by(AIWorkflow.updated_at.desc()).offset(offset).limit(limit) result = await db.execute(stmt) return result.scalars().all() @router.get("/interactions/", response_model=List[AIInteractionRead], dependencies=[Depends(get_current_staff_user)]) async def get_recent_interactions( db: AsyncSession = Depends(get_db), ticket_id: Optional[UUID] = None, offset: int = 0, limit: int = 25 ) -> List[AIInteraction]: """ Retrieves granular AI interaction traces with optional ticket filtering and pagination. """ stmt = select(AIInteraction) if ticket_id: stmt = stmt.where(AIInteraction.ticket_id == ticket_id) stmt = stmt.order_by(AIInteraction.created_at.desc()).offset(offset).limit(limit) result = await db.execute(stmt) return result.scalars().all() @router.get("/history/", response_model=List[MetaInfraHealthRead], dependencies=[Depends(get_current_staff_user)]) async def get_performance_history( db: AsyncSession = Depends(get_db) ) -> List[MetaInfraHealth]: """ Retrieves the last 24 hours of infrastructure health data. """ since = datetime.utcnow() - timedelta(hours=24) stmt = ( select(MetaInfraHealth) .where(MetaInfraHealth.created_at >= since) .order_by(MetaInfraHealth.created_at.asc()) ) result = await db.execute(stmt) return result.scalars().all()