"""cortex/api/routes/admin/observatory.py — Config Observatory endpoint."""

from __future__ import annotations

from datetime import datetime, timezone
from typing import Any

from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse

from cortex import __version__
from cortex.api.deps import PREFIX, get_plugin


def _register(router: APIRouter, verify_api_key):
    """Register observatory routes on the given router."""

    @router.get(
        f"{PREFIX}/admin/observatory",
        summary="Config Observatory",
        tags=["admin"],
        operation_id="get_observatory",
    )
    async def get_observatory(
        _: None = Depends(verify_api_key),
        plugin: Any = Depends(get_plugin),
    ):
        """Return Cortex's running configuration in a normalized schema.

        Provides a snapshot of all active config knobs — models, providers,
        rerank settings, and live storage counts — for observability and
        debugging without requiring server access.
        """
        cfg = plugin.config

        # Storage counts — query storage adapter directly for live counts.
        # Falls back to 0 gracefully if storage is unavailable.
        claims_count = 0
        sessions_count = 0
        cornerstones_count = 0

        report = await plugin.health()
        storage_status = report.storage  # "ok" | "unknown" | "error: ..."

        storage = getattr(plugin, "storage", None)
        if storage_status == "ok" and storage is not None:
            try:
                owner_id = getattr(cfg, "owner_id", "default")
                if hasattr(storage, "count_claims"):
                    claims_count = await storage.count_claims(owner_id=owner_id)
                if hasattr(storage, "count_sessions"):
                    sessions_count = await storage.count_sessions(owner_id=owner_id)
                if hasattr(storage, "get_cornerstones"):
                    cs = await storage.get_cornerstones(owner_id=owner_id)
                    cornerstones_count = len(cs) if cs else 0
            except Exception:
                pass  # graceful degradation — counts remain 0

        # dialectic falls back to extraction_model when not set
        dialectic_model = cfg.dialectic_model if cfg.dialectic_model else cfg.extraction_model

        return JSONResponse(content={
            "node": "cortex-prod",
            "version": __version__,
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "config": {
                "embeddings": {
                    "model": cfg.embedding_model,
                    "dim": cfg.embedding_dim,
                    "provider": cfg.provider_embedding_provider or "default",
                },
                "extraction": {
                    "model": cfg.extraction_model,
                    "enabled": cfg.extraction_enabled,
                    "prompt_version": cfg.extraction_prompt_version,
                },
                "reconciliation": {
                    "model": cfg.reconciliation_model,
                },
                "dialectic": {
                    "model": dialectic_model,
                },
                "rerank": {
                    "enabled": cfg.retrieval_rerank_enabled,
                    "model": cfg.retrieval_rerank_model,
                    "top_k": cfg.retrieval_rerank_top_k,
                },
                "llm": {
                    "provider_mode": cfg.provider_mode,
                    "provider_priority": cfg.llm_provider_priority,
                    "completion_model": cfg.provider_llm_model,
                },
                "storage": {
                    "claims_count": claims_count,
                    "sessions_count": sessions_count,
                    "cornerstones_count": cornerstones_count,
                },
            },
        })
