import json
import redis
import os
import logging

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))
SLOT_TTL = 1800


def _make_client():
    client = redis.Redis(
        host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB,
        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}"


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."""
    client = _get_redis()
    if not client:
        return None
    try:
        raw = client.get(_key(namespace, str(company_id), conversation_id))
        return json.loads(raw) if raw else None
    except Exception as e:
        logger.warning(f"Slot read failed [{namespace}]: {e}")
        return None


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


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