"""Every Redis-backed conversation-state store, checked from inside the running
app (GET /ping -> "redis_state_stores") and by scripts/redis_diagnose.py.

Why from inside the app: on a hosting-panel deployment (cPanel / Passenger) the
panel's environment variables reach the app's workers but not a shell, so a
script run by hand can see a healthy Redis while the app uses other settings.
Each store reads REDIS_* itself, at import; this reports what each one uses
(never the password - only whether one is set) and whether it can connect.
"""
from __future__ import annotations

import importlib
import logging

logger = logging.getLogger(__name__)

STATE_STORES = (
    "services.slot_store", "services.leave_slot_service", "services.leave_cancel_state",
    "services.leave_disambiguation_state", "services.leave_history_clarify_state",
    "services.leave_type_clarify_state", "services.leave_eligibility_clarify_state",
    "services.policy_draft_state", "services.regularisation_store", "services.redis_chat_service",
    "services.chat_inflight", "services.voice_rate_limit",
)


def check_state_stores() -> dict:
    """{"status": "ok"|"degraded", "stores": {short name: {...}}}. A ping per
    store, no writes."""
    stores, ok = {}, True
    for name in STATE_STORES:
        short = name.rsplit(".", 1)[-1]
        try:
            mod = importlib.import_module(name)
        except Exception as e:
            stores[short] = {"status": "error", "error": f"import: {type(e).__name__}"}
            ok = False
            continue
        entry = {"host": f"{getattr(mod, 'REDIS_HOST', '?')}:{getattr(mod, 'REDIS_PORT', '?')}",
                 "db": getattr(mod, "REDIS_DB", "?"),
                 "password_set": bool(getattr(mod, "REDIS_PASSWORD", None))}
        getter = getattr(mod, "_get_redis", None)
        client = getter() if getter else getattr(mod, "_r", None)
        if client is None:
            entry["status"] = "not_connected"
            ok = False
        else:
            try:
                client.ping()
                entry["status"] = "ok"
            except Exception as e:
                entry["status"] = "error"
                entry["error"] = type(e).__name__
                ok = False
        stores[short] = entry
    return {"status": "ok" if ok else "degraded", "stores": stores}
