"""Health checks (spec §69): /health, /ready, /provider-health, /database-health.

AUDIT NOTE (StockLab overhaul, final engineering pass, Part A3, docs/AUDIT_SECURITY_A3.md):
deliberately left WITHOUT rate limiting. These exist specifically to be polled frequently by an
orchestrator/load balancer/monitoring system (Podman/systemd healthchecks, docs/DEPLOYMENT.md) --
rate limiting a healthcheck endpoint risks the monitoring system itself tripping the limit and
misreporting a healthy service as down, which is a worse outcome than the negligible cost of these
routes (a constant SELECT 1 at worst) being polled often.
"""

from fastapi import APIRouter, Depends
from sqlalchemy import text
from sqlalchemy.orm import Session

from app.core.config import get_settings
from app.core.db import get_db

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


@router.get("/health")
def health():
    return {"status": "ok"}


@router.get("/database-health")
def database_health(db: Session = Depends(get_db)):
    try:
        db.execute(text("SELECT 1"))
        return {"status": "ok"}
    except Exception as e:  # pragma: no cover — exercised only against a real DB
        return {"status": "error", "detail": str(e)}


@router.get("/provider-health")
def provider_health():
    settings = get_settings()
    result = {"primary": settings.PROVIDER_PRIMARY, "secondary": settings.PROVIDER_SECONDARY}
    if settings.PROVIDER_PRIMARY == "FMP":
        result["primary_configured"] = bool(settings.FMP_API_KEY)
    if settings.PROVIDER_SECONDARY == "EODHD":
        result["secondary_configured"] = bool(settings.EODHD_API_KEY)
    return result


@router.get("/ready")
def ready(db: Session = Depends(get_db)):
    db_ok = database_health(db)["status"] == "ok"
    return {"status": "ok" if db_ok else "not_ready", "database": db_ok}
