from typing import Any, List, Dict, Optional from uuid import UUID from fastapi import APIRouter, Depends from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select, cast, String 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( workspace_id: Optional[UUID] = None, 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 @router.get("/workflows/", response_model=List[AIWorkflowRead], dependencies=[Depends(get_current_staff_user)]) async def get_recent_workflows( db: AsyncSession = Depends(get_db), workspace_id: Optional[UUID] = None, 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 workspace_id: stmt = stmt.where(AIWorkflow.workspace_id == workspace_id) 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), workspace_id: Optional[UUID] = None, ticket_id: Optional[str] = None, offset: int = 0, limit: int = 25 ) -> List[AIInteraction]: """ Retrieves granular AI interaction traces with optional ticket filtering and pagination. """ stmt = select(AIInteraction) if workspace_id: stmt = stmt.where(AIInteraction.workspace_id == workspace_id) if ticket_id: # Support partial UUID match or exact UUID try: # Try exact UUID first t_uuid = UUID(ticket_id) stmt = stmt.where(AIInteraction.ticket_id == t_uuid) except ValueError: # Fallback to partial string match on the UUID column stmt = stmt.where(cast(AIInteraction.ticket_id, String).ilike(f"{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), workspace_id: Optional[UUID] = None ) -> 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) ) # MetaInfraHealth is global, no workspace_id column stmt = stmt.order_by(MetaInfraHealth.created_at.asc()) result = await db.execute(stmt) return result.scalars().all() from models.audit_log import AuditLog from models.user import User from schemas.system import AuditLogRead @router.get("/audit/", response_model=List[AuditLogRead], dependencies=[Depends(get_current_staff_user)]) async def get_security_audit_logs( db: AsyncSession = Depends(get_db), workspace_id: Optional[UUID] = None, entity_type: Optional[str] = None, entity_id: Optional[str] = None, action: Optional[str] = None, limit: int = 50, offset: int = 0 ) -> Any: """ Retrieves security and administrative audit logs. Hydrates the actor name for UI display. """ stmt = ( select(AuditLog, User.full_name) .outerjoin(User, AuditLog.user_id == User.id) ) if workspace_id: stmt = stmt.where(AuditLog.workspace_id == workspace_id) if entity_type: stmt = stmt.where(AuditLog.entity_type == entity_type) if entity_id: try: e_uuid = UUID(entity_id) stmt = stmt.where(AuditLog.entity_id == e_uuid) except ValueError: stmt = stmt.where(cast(AuditLog.entity_id, String).ilike(f"{entity_id}%")) if action: stmt = stmt.where(AuditLog.action == action) stmt = stmt.order_by(AuditLog.created_at.desc()).offset(offset).limit(limit) result = await db.execute(stmt) logs = [] for log_obj, actor_name in result.all(): # Hydrate the virtual field setattr(log_obj, "actor_name", actor_name or "System/AI") logs.append(log_obj) return logs @router.get("/diagnostics/redis/", dependencies=[Depends(get_current_super_admin)]) async def redis_diagnostics(arq_pool: ArqRedis = Depends(get_arq_pool)): """ Superadmin-only diagnostic tool to inspect the state of the Arq/Redis backbone. """ keys = [] async for key in arq_pool.scan_iter("*"): keys.append(key.decode()) # Category counts jobs = [k for k in keys if k.startswith("arq:job:")] health = [k for k in keys if k.startswith("arq:health-check")] latch = [k for k in keys if k.startswith("job_latch:")] return { "summary": { "total_keys": len(keys), "jobs_total": len(jobs), "workers_health_keys": len(health), "latches_total": len(latch) }, "keys": keys[:200] # Return a sample } from pydantic import BaseModel class ManualTriageRequest(BaseModel): ticket_id: str @router.post("/triage/", dependencies=[Depends(get_current_super_admin)]) async def manual_triage( req: ManualTriageRequest, db: AsyncSession = Depends(get_db), current_user: User = Depends(get_current_super_admin) ): """ Manually trigger a triage workflow for a ticket ID (exact or partial). """ from agents.tools.nexus_tools import resolve_ticket_id from tasks.system import enqueue_task from fastapi import HTTPException role_str = str(current_user.role.value if hasattr(current_user.role, 'value') else current_user.role) ws_id = current_user.workspace_id or "00000000-0000-0000-0000-000000000000" # dummy if None, staff gets global fallback # Needs a dummy UUID if None, but since staff do global searches, it's fine. from uuid import UUID t_obj = await resolve_ticket_id(db, req.ticket_id, UUID(str(ws_id)), role=role_str) if not t_obj: raise HTTPException(status_code=404, detail=f"Ticket {req.ticket_id} not found or ambiguous.") actual_t_id, actual_ws_id = t_obj job_id = await enqueue_task("run_ai_workflow", actual_t_id, actual_ws_id, job_id=f"ai_workflow_manual_{actual_t_id}") if not job_id: raise HTTPException(status_code=500, detail="Failed to enqueue manual triage job.") return {"status": "success", "job_id": job_id, "ticket_id": actual_t_id}