from typing import Any, List, Dict from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select, func, desc from datetime import datetime, timedelta import asyncio import time from core.deps import get_db, get_current_staff_user, get_arq_pool from core.config import get_settings from models.user import User from models.ai_workflow import AIWorkflow from models.ai_interaction import AIInteraction from models.meta_infra_health import MetaInfraHealth, ServiceStatus 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_staff_user)]) 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. """ # 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": 0}, "redis": {"status": infra_health["redis"], "latency_ms": 0, "pending_jobs": 0}, "ollama": {"status": "DOWN", "latency_ms": 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, List, Dict, Optional from core.deps import get_db, get_current_staff_user, get_arq_pool ... @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()