"""API v2 health and monitoring endpoints."""

from datetime import datetime
from typing import Optional

from fastapi import APIRouter, Depends, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import text

from src.api.deps import get_db
from src.core.cache import cache_manager
from src.core.monitoring import metrics, metrics_endpoint
from src.core.config import settings


router = APIRouter()


@router.get("/live")
async def liveness_check():
    """Kubernetes liveness probe.

    Returns 200 if the application is running.
    """
    return {
        "status": "alive",
        "timestamp": datetime.utcnow().isoformat(),
    }


@router.get("/ready")
async def readiness_check(db: AsyncSession = Depends(get_db)):
    """Kubernetes readiness probe.

    Returns 200 if the application is ready to serve requests.
    Checks database and cache connectivity.
    """
    checks = {}
    healthy = True

    # Check database
    try:
        result = await db.execute(text("SELECT 1"))
        result.scalar()
        checks["database"] = "healthy"
    except Exception as e:
        checks["database"] = f"unhealthy: {str(e)}"
        healthy = False

    # Check cache
    try:
        await cache_manager.initialize()
        cache_stats = await cache_manager.get_stats()
        checks["cache"] = "healthy"
        checks["cache_stats"] = cache_stats
    except Exception as e:
        checks["cache"] = f"unhealthy: {str(e)}"
        healthy = False

    status_code = status.HTTP_200_OK if healthy else status.HTTP_503_SERVICE_UNAVAILABLE

    return {
        "status": "healthy" if healthy else "unhealthy",
        "timestamp": datetime.utcnow().isoformat(),
        "checks": checks,
    }


@router.get("/startup")
async def startup_check():
    """Kubernetes startup probe.

    Returns 200 when the application has started.
    """
    return {
        "status": "started",
        "timestamp": datetime.utcnow().isoformat(),
        "version": getattr(settings, "app_version", "1.0.0"),
    }


@router.get("/metrics")
async def prometheus_metrics():
    """Prometheus metrics endpoint."""
    return await metrics_endpoint()


@router.get("/info")
async def app_info():
    """Application information endpoint."""
    return {
        "name": getattr(settings, "app_name", "mockupAWS"),
        "version": getattr(settings, "app_version", "1.0.0"),
        "environment": "production"
        if not getattr(settings, "debug", False)
        else "development",
        "timestamp": datetime.utcnow().isoformat(),
    }
