"""Why does Redis-backed conversation state get lost on this server?

Run ON THE SERVER, from the app's folder, with the app's own Python:

    cd <app folder>            # the folder with main.py and .env
    venv/bin/python scripts/redis_diagnose.py

Read-only apart from one test key per store (written, read back, deleted).
Prints no passwords or tokens - only whether they are set.

What it checks, and what each finding would explain:
  1. Settings: what every state store actually uses (host/port/db, password
     set or not), and whether REDIS_* came from the process environment
     rather than .env (load_dotenv never overrides those - a stale value set
     by the hosting panel or service file wins silently).
  2. Connection: each store connects, and a write is read back.
  3. The Redis server: restarts (uptime) without persistence wipe every key;
     a full memory with an eviction policy drops keys; a read-only replica
     refuses writes; a different db/host than UAT.
"""
import json
import os
import sys
import time
import uuid

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
os.chdir(ROOT)

REDIS_VARS = ("REDIS_HOST", "REDIS_PORT", "REDIS_DB", "REDIS_USERNAME", "REDIS_PASSWORD")
from_process = {k: (k in os.environ) for k in REDIS_VARS}

from dotenv import dotenv_values, load_dotenv  # noqa: E402

in_dotenv = dotenv_values(os.path.join(ROOT, ".env"))
load_dotenv(os.path.join(ROOT, ".env"))

from services.redis_health import STATE_STORES as STORES  # noqa: E402  (one list, as /ping)
findings = []


def finding(text):
    findings.append(text)


def show(title):
    print(f"\n== {title}")


# ── 1. settings ─────────────────────────────────────────────────────────────
show("1. Redis settings the app sees (no secrets)")
for k in REDIS_VARS:
    value = os.environ.get(k)
    shown = ("set" if value else "NOT SET") if k in ("REDIS_PASSWORD", "REDIS_USERNAME") else (value or "(default)")
    source = ("process environment" if from_process[k] else ".env" if k in in_dotenv else "code default")
    print(f"  {k:15} = {shown:20} from: {source}")
    if from_process[k] and k in in_dotenv and str(in_dotenv[k]) != os.environ.get(k):
        finding(f"{k} in the process environment DIFFERS from .env - the process value wins "
                f"(load_dotenv does not override). Fix the hosting panel / service file, or remove it there.")

# ── 2. each store ───────────────────────────────────────────────────────────
show("2. Each state store: its settings, connection, and a write read back")
import importlib  # noqa: E402

seen_configs = set()
for name in STORES:
    try:
        mod = importlib.import_module(name)
    except Exception as e:
        print(f"  {name:42} IMPORT FAILED: {type(e).__name__}: {e}")
        continue
    cfg = (getattr(mod, "REDIS_HOST", "?"), getattr(mod, "REDIS_PORT", "?"), getattr(mod, "REDIS_DB", "?"),
           bool(getattr(mod, "REDIS_PASSWORD", None)))
    seen_configs.add(cfg)
    getter = getattr(mod, "_get_redis", None)
    client = getter() if getter else getattr(mod, "_r", None)
    if client is None:
        print(f"  {name:42} host={cfg[0]}:{cfg[1]} db={cfg[2]} password={'yes' if cfg[3] else 'no'}  "
              f"-> NOT CONNECTED")
        finding(f"{name} cannot connect - its state silently does nothing (or lives only in this "
                f"process's memory). See its host/port/password above.")
        continue
    key = f"diag:{uuid.uuid4().hex}"
    try:
        client.set(key, "1", ex=60)
        back = client.get(key)
        ttl = client.ttl(key)
        client.delete(key)
        ok = str(back) in ("1", "b'1'")
        print(f"  {name:42} host={cfg[0]}:{cfg[1]} db={cfg[2]} password={'yes' if cfg[3] else 'no'}  "
              f"-> {'OK' if ok else 'WRITE NOT READ BACK'} (ttl {ttl})")
        if not ok:
            finding(f"{name}: a written key was not read back.")
    except Exception as e:
        print(f"  {name:42} -> ERROR on write/read: {type(e).__name__}: {e}")
        finding(f"{name}: write/read fails: {type(e).__name__}: {e}")
if len(seen_configs) > 1:
    finding(f"The stores do NOT all use the same Redis settings: {sorted(seen_configs)}")

# ── 3. the Redis server ─────────────────────────────────────────────────────
show("3. The Redis server")
client = None
for name in STORES:
    mod = sys.modules.get(name)
    getter = getattr(mod, "_get_redis", None) if mod else None
    client = getter() if getter else None
    if client is not None:
        break
if client is None:
    print("  no store could connect - nothing more to check")
else:
    def info(section):
        try:
            return client.info(section)
        except Exception as e:
            print(f"  INFO {section}: not allowed ({e})")
            return {}

    server, memory, stats, persistence, repl, keyspace = (
        info("server"), info("memory"), info("stats"), info("persistence"), info("replication"), info("keyspace"))
    uptime = int(server.get("uptime_in_seconds", 0) or 0)
    print(f"  version            {server.get('redis_version')}")
    print(f"  uptime             {uptime // 86400}d {(uptime % 86400) // 3600}h {(uptime % 3600) // 60}m")
    print(f"  role               {repl.get('role')}")
    print(f"  memory used / max  {memory.get('used_memory_human')} / "
          f"{memory.get('maxmemory_human') or memory.get('maxmemory')} ({memory.get('maxmemory_policy')})")
    print(f"  evicted keys       {stats.get('evicted_keys')}")
    print(f"  expired keys       {stats.get('expired_keys')}")
    print(f"  persistence        rdb_last_save={persistence.get('rdb_last_save_time')} "
          f"aof_enabled={persistence.get('aof_enabled')} "
          f"rdb_changes_since_save={persistence.get('rdb_changes_since_last_save')}")
    print(f"  keyspace           {json.dumps(keyspace)}")
    if repl.get("role") not in (None, "master"):
        finding("This Redis is a REPLICA (read-only): every write from the app fails.")
    if int(stats.get("evicted_keys") or 0) > 0:
        finding(f"Redis has EVICTED {stats.get('evicted_keys')} keys (memory full, policy "
                f"{memory.get('maxmemory_policy')}): conversation state is being dropped. Raise maxmemory, "
                f"or use 'volatile-lru' and give the cache its own db.")
    if uptime and uptime < 2 * 86400:
        finding(f"Redis restarted {uptime // 3600}h ago. Without persistence (AOF/RDB) a restart wipes "
                f"every conversation's state - check how often it restarts.")
    if not persistence.get("aof_enabled") and not persistence.get("rdb_last_save_time"):
        finding("No persistence (AOF off, no RDB save): any Redis restart loses all state.")

# ── summary ─────────────────────────────────────────────────────────────────
show("Findings")
if findings:
    for f in findings:
        print(f"  * {f}")
else:
    print("  Nothing wrong found from this process. If the app still forgets on this server, the app's")
    print("  worker processes may not see the same environment as this shell - compare with the service")
    print("  config (systemd unit / hosting panel) and run this script as the same user the app runs as.")
print(f"\n(checked at {time.strftime('%Y-%m-%d %H:%M:%S')}, pid {os.getpid()})")
