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))
# 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
# 10 min — LLD's recommended 5-10 min confirmation window. Longer than
# leave_clarify_state's 300s (this covers both selection AND confirmation,
# not just one clarifying reply); shorter than leave_slot_service's 1800s
# (there's no open-ended slot collection here, just picking a request and
# confirming it).
CANCEL_STATE_TTL = 600


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 leave-cancel store connected")
except Exception as e:
    logger.warning(f"Redis leave-cancel store unavailable: {e} — cancel-leave conversations won't persist mid-flow")
    _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-cancel store reconnected")
    except Exception:
        pass
    return _r


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


def get_state(company_id, conversation_id: str) -> dict | None:
    """Returns the in-progress cancel-leave state ({"step": "awaiting_selection",
    "candidates": [...]} or {"step": "awaiting_confirmation", "selected": {...}}),
    or None if there is none (no mid-flow conversation, expired TTL, or Redis
    unavailable)."""
    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-cancel state read failed: {e}")
        return None


def set_state(company_id, conversation_id: str, state: dict) -> bool:
    """Returns True once the write is confirmed, False if Redis is
    unavailable or the write failed."""
    client = _get_redis()
    if not client:
        return False
    try:
        client.set(_key(str(company_id), conversation_id), json.dumps(state), ex=CANCEL_STATE_TTL)
        return True
    except Exception as e:
        logger.warning(f"Leave-cancel state write failed: {e}")
        return False


def clear_state(company_id, conversation_id: str) -> bool:
    """Returns True once the delete is confirmed, False if Redis is
    unavailable or the delete failed."""
    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-cancel state clear failed: {e}")
        return False