"""Health check and readiness API endpoints.

Two separate endpoints for Kubernetes probes:
- /health  (livenessProbe)  → Always returns 200 if process is alive.
                               If this fails, K8s RESTARTS the pod.
- /ready   (readinessProbe) → Returns 200 if pod can accept new sessions.
                               Returns 503 when draining after max sessions.
                               If this fails, K8s removes pod from Service
                               endpoints (ALB stops sending new traffic).
                               Active sessions continue running normally.
"""

from datetime import datetime
from fastapi import APIRouter
from fastapi.responses import JSONResponse

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


@router.get("/health")
async def health_check():
    """Liveness probe - returns 200 if the process is running.
    
    Used by Kubernetes livenessProbe. Always returns 200 unless
    the process is truly broken. Does NOT check resource usage
    (that's the readiness probe's job).
    """
    from utils.turso_client import get_stt_mode, get_gcp_mode, get_gcp_new_account_percentage
    from utils.redis_client import redis_health, redis_available
    from utils.cache_layer import get_cache_stats
    from utils.resource_monitor import get_memory_usage, get_cpu_usage
    from utils.pod_lifecycle import get_lifecycle_stats
    from routes.bot import active_sessions

    gcp_mode = get_gcp_mode()
    gcp_info = gcp_mode if gcp_mode != "random" else f"random({get_gcp_new_account_percentage()}% new)"

    response = {
        "status": "healthy",
        "service": "maya-global-agent",
        "timestamp": datetime.now().isoformat(),
        "active_sessions": len(active_sessions),
        "lifecycle": get_lifecycle_stats(),
        "resources": {
            "memory": get_memory_usage(),
            "cpu": get_cpu_usage(),
        },
        "features": {
            "language": "hi",
            "voice": "taru",
            "stt": get_stt_mode(),
            "gcp": gcp_info,
            "capabilities": ["image", "edit_image", "characters"]
        },
        "cache": {
            "redis_enabled": redis_available(),
            **get_cache_stats(),
        }
    }

    # Add detailed Redis health (only if Redis is configured)
    if redis_available():
        response["cache"]["redis"] = await redis_health()

    return response


@router.get("/ready")
async def readiness_check():
    """Readiness probe - returns 503 when pod is draining after max sessions.
    
    Returns 200 normally. After completing MAX_POD_SESSIONS (default 1000),
    returns 503 so K8s stops routing new traffic. Active sessions continue
    until they finish, then the pod exits and K8s restarts a fresh one.
    """
    from routes.bot import active_sessions
    from utils.pod_lifecycle import is_draining, get_lifecycle_stats

    result = {
        "timestamp": datetime.now().isoformat(),
        "active_sessions": len(active_sessions),
        "lifecycle": get_lifecycle_stats(),
    }

    if is_draining():
        result["status"] = "draining"
        result["ready"] = False
        return JSONResponse(status_code=503, content=result)

    result["status"] = "ready"
    result["ready"] = True
    return result
