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))
# Short TTL on purpose — this must be answered in the same conversational
# beat as the clarifying question, not resumed minutes later out of context.
LEAVE_TYPE_CLARIFY_STATE_TTL = 300


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 leave-type-clarify-state store connected")
except Exception as e:
    logger.warning(f"Redis leave-type-clarify-state store unavailable: {e} — 'sick leave' style bare-mention follow-ups won't be tracked")
    _r = None


def _get_redis():
    """Return live Redis client, attempting reconnect if previously unavailable."""
    global _r
    if _r is not None:
        return _r
    try:
        _r = _make_client()
        logger.info("Redis leave-type-clarify-state store reconnected")
    except Exception:
        pass
    return _r


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


def get_state(company_id, conversation_id: str) -> dict | None:
    """Returns {"leave_type_slug": str} while the assistant's last turn asked
    'would you like your balance/eligibility/apply/status for <type> leave?'
    and is still waiting on the answer, or None if there's no pending
    question (no clarify in progress, expired TTL, or Redis unavailable).
    Fails closed: worst case, the follow-up reply gets classified normally
    instead of being interpreted as an answer to a question that was never
    durably recorded."""
    client = _get_redis()
    if not client:
        return None
    try:
        raw = client.get(_key(str(company_id), conversation_id))
        return json.loads(raw) if raw else None
    except Exception as e:
        logger.warning(f"Leave-type-clarify-state read failed: {e}")
        return None


def set_state(company_id, conversation_id: str, state: dict) -> bool:
    client = _get_redis()
    if not client:
        return False
    try:
        client.set(_key(str(company_id), conversation_id), json.dumps(state), ex=LEAVE_TYPE_CLARIFY_STATE_TTL)
        return True
    except Exception as e:
        logger.warning(f"Leave-type-clarify-state write failed: {e}")
        return False


def clear_state(company_id, conversation_id: str) -> bool:
    client = _get_redis()
    if not client:
        return False
    try:
        client.delete(_key(str(company_id), conversation_id))
        return True
    except Exception as e:
        logger.warning(f"Leave-type-clarify-state clear failed: {e}")
        return False
