"""Health check route"""

from fastapi import APIRouter, Request

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


@router.get("/health")
async def health_check(request: Request):
    """Enhanced health check with dependency status"""
    app = request.app
    checks: dict = {}
    overall_status = "healthy"

    # Check Redis / TaskStore backend
    redis_status = "not_configured"
    try:
        task_store = getattr(app.state, "task_store", None)
        if task_store:
            if task_store.backend_type == "redis":
                # Verify connectivity with PING
                try:
                    redis_client = await task_store._get_redis()
                    await redis_client.ping()
                    redis_status = "available"
                except Exception as ping_exc:
                    redis_status = f"error: {str(ping_exc)[:100]}"
                    overall_status = "degraded"
            else:
                redis_status = "not_configured"
        else:
            redis_status = "not_configured"
    except Exception as exc:
        redis_status = f"error: {str(exc)[:100]}"
        overall_status = "degraded"
    checks["redis"] = redis_status

    # Check AgentPool
    agent_pool = getattr(app.state, "agent_pool", None)
    pool_size = 0
    if agent_pool:
        try:
            agents = agent_pool.list_agents()
            pool_size = len(agents)
        except Exception:
            pass
    checks["agent_pool"] = {"status": "available", "size": pool_size}

    # Check LLM Gateway
    llm_gateway = getattr(app.state, "llm_gateway", None)
    llm_status = "not_configured"
    if llm_gateway:
        llm_status = "configured"
        try:
            if llm_gateway.has_providers:
                llm_status = "available"
            else:
                llm_status = "no_providers"
                overall_status = "degraded"
        except Exception:
            llm_status = "error"
            overall_status = "degraded"
    checks["llm_gateway"] = llm_status

    # Check Skill Registry
    skill_registry = getattr(app.state, "skill_registry", None)
    skill_count = 0
    if skill_registry:
        try:
            skill_count = len(skill_registry.list_skills())
        except Exception:
            pass
    checks["skill_registry"] = {
        "status": "available" if skill_registry else "not_configured",
        "count": skill_count,
    }

    return {
        "status": overall_status,
        "version": "2.0.0",
        "checks": checks,
    }
