import json
import redis
import os
import logging
import threading
import time

logger = logging.getLogger(__name__)

REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
REDIS_PORT = int(os.getenv("REDIS_PORT", 6379))
REDIS_DB = int(os.getenv("REDIS_DB", 0))
# Optional: only sent when set, so an unauthenticated Redis behaves as before.
# Production Redis is password-protected — without these this store fails its
# connect-time ping() and every get/set below silently no-ops, which reads as
# the flow "forgetting" mid-conversation rather than as an outage.
REDIS_PASSWORD = os.getenv("REDIS_PASSWORD") or None
REDIS_USERNAME = os.getenv("REDIS_USERNAME") or None
SLOT_TTL = 1800


def _make_client():
    client = redis.Redis(
        host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB,
        username=REDIS_USERNAME, password=REDIS_PASSWORD,
        decode_responses=True, socket_connect_timeout=3,
        socket_timeout=3, retry_on_timeout=True,
    )
    client.ping()
    return client


try:
    _r = _make_client()
    logger.info("✓ Redis slot store connected")
except Exception as e:
    logger.warning(f"Redis slot store unavailable: {e} — multi-turn slot-filling conversations won't persist mid-flow")
    _r = None


def _get_redis():
    global _r
    if _r is not None:
        return _r
    try:
        _r = _make_client()
        logger.info("Redis slot store reconnected")
    except Exception:
        pass
    return _r


def _key(namespace: str, company_id, conversation_id: str) -> str:
    return f"{namespace}_slots:{company_id}:{conversation_id}"


# ── In-process fallback ──────────────────────────────────────────────────────
# Every write is also kept here, and a read falls back to it whenever Redis is
# unreachable or errors. Without it, a Redis this process cannot reach turned
# every get/set/clear into a silent no-op: the flow forgot its own state
# between turns while chat history — which has a Postgres fallback — looked
# fine. Live (regularization): "Confirm & Submit" re-showed the summary and
# the "yes" after it answered "I don't have any regularization details to
# submit yet", because the complete, confirmed entry was never read back.
#
# Per-process, so with several workers it only helps a turn that lands on the
# same one; it is a floor under a Redis outage, not a replacement for Redis.
# Same TTL as the Redis keys.
_memory: dict = {}
_memory_lock = threading.Lock()


def _memory_set(key: str, raw: str) -> None:
    with _memory_lock:
        _memory[key] = (time.monotonic() + SLOT_TTL, raw)


def _memory_get(key: str):
    with _memory_lock:
        item = _memory.get(key)
        if item is None:
            return None
        expires_at, raw = item
        if expires_at < time.monotonic():
            _memory.pop(key, None)
            return None
        return raw


def _memory_clear(key: str) -> None:
    with _memory_lock:
        _memory.pop(key, None)


def get_slots(namespace: str, company_id, conversation_id: str) -> dict | None:
    """namespace distinguishes flows sharing one Redis instance, e.g.
    "leave", "regularization", "leave_policy_exception" — each gets its
    own key prefix so their mid-flow state never collides."""
    key = _key(namespace, str(company_id), conversation_id)
    client = _get_redis()
    raw = None
    if client:
        try:
            raw = client.get(key)
        except Exception as e:
            logger.warning(f"Slot read failed [{namespace}]: {e} — using the in-process copy")
            raw = _memory_get(key)
    else:
        raw = _memory_get(key)
    try:
        return json.loads(raw) if raw else None
    except (TypeError, ValueError):
        return None


def set_slots(namespace: str, company_id, conversation_id: str, slots: dict) -> None:
    key = _key(namespace, str(company_id), conversation_id)
    raw = json.dumps(slots)
    _memory_set(key, raw)
    client = _get_redis()
    if not client:
        return
    try:
        client.set(key, raw, ex=SLOT_TTL)
    except Exception as e:
        logger.warning(f"Slot write failed [{namespace}]: {e} — kept in-process only")


def clear_slots(namespace: str, company_id, conversation_id: str) -> None:
    key = _key(namespace, str(company_id), conversation_id)
    _memory_clear(key)
    client = _get_redis()
    if not client:
        return
    try:
        client.delete(key)
    except Exception as e:
        logger.warning(f"Slot clear failed [{namespace}]: {e}")