from fastapi import APIRouter, Depends
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app import __version__
from app.api.deps import get_db
from app.core.config import settings
from app.core.database import engine
from app.providers import supported_channels
from app.services.monitoring_service import CapabilityService

router = APIRouter()


@router.get("/health")
async def health_check():
    """Liveness probe — does not touch the database."""
    return {
        "status": "ok",
        "service": settings.service_name,
        "version": __version__,
        "channels": [c["channel"] for c in supported_channels() if c["status"] == "active"],
    }


@router.get("/health/ready")
async def readiness_check(session: AsyncSession = Depends(get_db)):
    """Readiness probe — verifies database connectivity."""
    try:
        await session.execute(select(1))
        db_ok = True
    except Exception:  # noqa: BLE001
        db_ok = False
    status = "ok" if db_ok else "degraded"
    return {
        "status": status,
        "service": settings.service_name,
        "version": __version__,
        "database": "up" if db_ok else "down",
        "engine": str(engine.url).split("@")[-1] if engine.url else "unknown",
    }


@router.get("/capabilities")
async def capabilities():
    return CapabilityService().capabilities()


@router.get("/metrics")
async def metrics_root():
    """Service-level metrics summary (no tenant). Use /api/v1/monitoring/metrics for tenant metrics."""
    return {
        "service": settings.service_name,
        "version": __version__,
        "hint": "GET /api/v1/monitoring/metrics with X-Tenant-ID for tenant metrics",
        "features": CapabilityService().capabilities()["features"],
    }
