"""Metrics route — /api/v1/metrics"""

import logging

from fastapi import APIRouter, Request

logger = logging.getLogger(__name__)

router = APIRouter(tags=["metrics"])


@router.get("/metrics")
async def get_metrics(request: Request):
    """Get application metrics"""
    app = request.app

    # Task metrics from TaskStore
    task_store = getattr(app.state, "task_store", None)
    task_metrics = {
        "total_tasks": 0,
        "completed_tasks": 0,
        "failed_tasks": 0,
        "pending_tasks": 0,
    }
    if task_store:
        try:
            counts = task_store.count_by_status()
            task_metrics["total_tasks"] = sum(counts.values())
            task_metrics["completed_tasks"] = counts.get("completed", 0)
            task_metrics["failed_tasks"] = counts.get("failed", 0)
            task_metrics["pending_tasks"] = counts.get("pending", 0)
        except Exception as e:
            logger.warning(f"Failed to collect task metrics: {e}")

    # Agent pool metrics
    agent_pool = getattr(app.state, "agent_pool", None)
    agent_metrics: dict = {
        "total_agents": 0,
    }
    if agent_pool:
        try:
            agents = agent_pool.list_agents()
            agent_metrics["total_agents"] = len(agents)
        except Exception as e:
            logger.warning(f"Failed to collect agent metrics: {e}")

    # Skill registry metrics
    skill_registry = getattr(app.state, "skill_registry", None)
    skill_metrics: dict = {
        "total_skills": 0,
    }
    if skill_registry:
        try:
            skills = skill_registry.list_skills()
            skill_metrics["total_skills"] = len(skills)
        except Exception as e:
            logger.warning(f"Failed to collect skill metrics: {e}")

    return {
        "tasks": task_metrics,
        "agents": agent_metrics,
        "skills": skill_metrics,
        "version": "2.0.0",
    }
