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))
# None when unset, which is what redis-py wants for an unauthenticated
# server - so an environment without a password behaves as it always did.
# REDIS_USERNAME is only needed for a Redis 6+ ACL user; a plain
# `requirepass` server authenticates as "default" with the password alone.
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 leave-slot store connected")
except Exception as e:
    logger.warning(f"Redis leave-slot store unavailable: {e} — apply-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-slot store reconnected")
    except Exception:
        pass
    return _r


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


# ── In-process fallback ──────────────────────────────────────────────────────
# The same floor slot_store has had since 29 Sep. Every write is also kept
# here, and a read falls back to it whenever Redis is unreachable or errors.
# Without it an apply-leave draft vanished the moment Redis did: the "yes" to
# "Shall I submit this request?" found nothing and started a brand-new
# application ("What type of leave would you like?") - negative run, 28 Oct,
# #63a, while a regularization draft in slot_store survived the same outage.
#
# Per-process, so with several workers it only helps a turn that lands on the
# same one. The return values still report what Redis did, which is what the
# post-submit clear retry (leave_action_service) keys off.
_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(company_id, conversation_id: str) -> dict | None:
    """Returns the in-progress apply-leave slot state, or None if there is
    none. Redis first; the in-process copy when Redis can't answer."""
    key = _key(str(company_id), conversation_id)
    client = _get_redis()
    raw = None
    if client:
        try:
            raw = client.get(key)
        except Exception as e:
            logger.warning(f"Leave-slot read failed: {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(company_id, conversation_id: str, slots: dict) -> bool:
    """Returns True once the write is confirmed, False if Redis is
    unavailable or the write failed — callers on a critical path (e.g.
    post-submission cleanup) should check this rather than assume success.
    The in-process copy is kept either way."""
    key = _key(str(company_id), conversation_id)
    raw = json.dumps(slots)
    _memory_set(key, raw)
    client = _get_redis()
    if not client:
        return False
    try:
        client.set(key, raw, ex=SLOT_TTL)
        return True
    except Exception as e:
        logger.warning(f"Leave-slot write failed: {e} — kept in-process only")
        return False


def clear_slots(company_id, conversation_id: str) -> bool:
    """Returns True once the delete is confirmed, False if Redis is
    unavailable or the delete failed. The in-process copy goes either way."""
    key = _key(str(company_id), conversation_id)
    _memory_clear(key)
    client = _get_redis()
    if not client:
        return False
    try:
        client.delete(key)
        return True
    except Exception as e:
        logger.warning(f"Leave-slot clear failed: {e}")
        return False


# -- Individual-report subject state (FR-07.3) -------------------------------
# Shares this module's Redis client, TTL and reconnect discipline rather than
# opening a second pool for what is the same thing: conversation-scoped state
# that must survive between two turns and expire on its own.
#
# Distinct key prefix, so an in-progress apply-leave flow and a pending
# employee selection can coexist in one conversation without either
# clobbering the other.
#
# Holds two things:
#   step == "awaiting_employee_selection" + candidates[] -> AC2 is mid-flow;
#       the next turn's reply is a selection, not a new question.
#   last_employee -> the most recently resolved subject, so a follow-up
#       phrased with a pronoun ("why was HE marked half-day?") still knows
#       who "he" is.


def _report_key(company_id, conversation_id: str) -> str:
    return f"individual_report:{company_id}:{conversation_id}"


def get_report_state(company_id, conversation_id: str) -> dict | None:
    """Pending employee selection and/or last resolved subject for this
    conversation, or None when there is none (or Redis is unavailable)."""
    client = _get_redis()
    if not client:
        return None
    try:
        raw = client.get(_report_key(str(company_id), conversation_id))
        return json.loads(raw) if raw else None
    except Exception as e:
        logger.warning(f"Individual-report state read failed: {e}")
        return None


def set_report_state(company_id, conversation_id: str, state: dict) -> bool:
    """False when Redis is unavailable or the write failed. A caller that
    just showed AC2's selection cards must treat False as "the follow-up
    won't resolve" and say so, rather than assume the selection will stick."""
    client = _get_redis()
    if not client:
        return False
    try:
        client.set(_report_key(str(company_id), conversation_id), json.dumps(state), ex=SLOT_TTL)
        return True
    except Exception as e:
        logger.warning(f"Individual-report state write failed: {e}")
        return False


def clear_report_state(company_id, conversation_id: str) -> bool:
    client = _get_redis()
    if not client:
        return False
    try:
        client.delete(_report_key(str(company_id), conversation_id))
        return True
    except Exception as e:
        logger.warning(f"Individual-report state clear failed: {e}")
        return False


# -- Manager-role flag cache (FR-07.3 gate) ----------------------------------
# The manager gate runs ahead of intent classification on EVERY turn, so the
# erp-api fallback it depends on would otherwise be paid once per message for
# any token whose JWT carries no role claim. The answer is a property of the
# caller, not of the question, and cannot change mid-conversation — so it is
# cached per conversation and the round trip happens at most once.
#
# Only a definite True/False is stored. An "unknown" (erp-api unreachable) is
# deliberately NOT cached: caching it would pin an outage-time answer to the
# rest of the conversation, refusing a real manager long after erp-api came
# back.


def _manager_flag_key(company_id, conversation_id: str) -> str:
    return f"manager_flag:{company_id}:{conversation_id}"


def get_manager_flag(company_id, conversation_id: str) -> bool | None:
    """Cached erp-api is_manager answer for this conversation, or None when
    it hasn't been resolved yet (or Redis is unavailable)."""
    client = _get_redis()
    if not client:
        return None
    try:
        raw = client.get(_manager_flag_key(str(company_id), conversation_id))
        if raw is None:
            return None
        return json.loads(raw) is True
    except Exception as e:
        logger.warning(f"Manager-flag read failed: {e}")
        return None


def set_manager_flag(company_id, conversation_id: str, is_manager: bool) -> bool:
    """False when Redis is unavailable or the write failed — the caller
    simply pays the erp-api round trip again next turn, which is correct,
    just not free."""
    client = _get_redis()
    if not client:
        return False
    try:
        client.set(_manager_flag_key(str(company_id), conversation_id),
                   json.dumps(bool(is_manager)), ex=SLOT_TTL)
        return True
    except Exception as e:
        logger.warning(f"Manager-flag write failed: {e}")
        return False


# The same answer, for the same reasons, about the caller's HR role —
# erp-api reports is_manager and is_hr in ONE response (/leave/context), so
# caching only half of it would mean paying that round trip again the moment
# anything asked about the other half.
#
# A second key rather than a widened value: the manager flag above is read on
# the path of every message, and a format change there is the kind that fails
# silently against entries already in Redis (a cached `true` would come back
# as a dict-shaped read). Same TTL, same "definite True/False only" rule —
# an unknown is not cached, so an outage cannot pin a wrong answer to the
# rest of the conversation.


def _hr_flag_key(company_id, conversation_id: str) -> str:
    return f"hr_flag:{company_id}:{conversation_id}"


def get_hr_flag(company_id, conversation_id: str) -> bool | None:
    """Cached erp-api is_hr answer for this conversation, or None when it
    hasn't been resolved yet (or Redis is unavailable)."""
    client = _get_redis()
    if not client:
        return None
    try:
        raw = client.get(_hr_flag_key(str(company_id), conversation_id))
        if raw is None:
            return None
        return json.loads(raw) is True
    except Exception as e:
        logger.warning(f"HR-flag read failed: {e}")
        return None


def set_hr_flag(company_id, conversation_id: str, is_hr: bool) -> bool:
    """False when Redis is unavailable or the write failed — same cost-only
    consequence as set_manager_flag."""
    client = _get_redis()
    if not client:
        return False
    try:
        client.set(_hr_flag_key(str(company_id), conversation_id),
                   json.dumps(bool(is_hr)), ex=SLOT_TTL)
        return True
    except Exception as e:
        logger.warning(f"HR-flag write failed: {e}")
        return False


# -- Pending manager action (FR-07.4) ----------------------------------------
# The confirmation step FR-08.3 requires is, mechanically, a two-turn
# conversation: turn one shows the card, turn two executes. What has to
# survive between them is WHICH request was confirmed — and it has to be the
# server's own record of it, never re-derived from the confirming message
# ("yes" names nothing).
#
# Same client, TTL and reconnect discipline as the two blocks above, and a
# third distinct key prefix so an in-progress apply-leave draft, a pending
# employee selection and a pending approval can coexist in one conversation.
#
# The TTL is a safety property here, not just housekeeping: a confirmation
# card that nobody answered must expire rather than sit waiting for a "yes"
# in some unrelated conversation half an hour later.


def _manager_action_key(company_id, conversation_id: str) -> str:
    return f"manager_action:{company_id}:{conversation_id}"


def get_manager_action(company_id, conversation_id: str) -> dict | None:
    """The action this conversation is awaiting confirmation for, or None."""
    client = _get_redis()
    if not client:
        return None
    try:
        raw = client.get(_manager_action_key(str(company_id), conversation_id))
        return json.loads(raw) if raw else None
    except Exception as e:
        logger.warning(f"Manager-action read failed: {e}")
        return None


def set_manager_action(company_id, conversation_id: str, action: dict) -> bool:
    """False when Redis is unavailable or the write failed. A caller that is
    about to show a confirmation card MUST check this: without the stored
    action there is nothing for a "yes" to resolve against, and the honest
    move is to say so rather than show a card whose confirmation will
    silently do nothing."""
    client = _get_redis()
    if not client:
        return False
    try:
        client.set(_manager_action_key(str(company_id), conversation_id),
                   json.dumps(action), ex=SLOT_TTL)
        return True
    except Exception as e:
        logger.warning(f"Manager-action write failed: {e}")
        return False


def clear_manager_action(company_id, conversation_id: str) -> bool:
    """False when Redis is unavailable or the delete failed — see
    leave_approval.py, which treats a failed clear after an executed
    approval as something to defuse, not ignore: a surviving
    awaiting_confirmation state is what a second "yes" would re-execute
    against."""
    client = _get_redis()
    if not client:
        return False
    try:
        client.delete(_manager_action_key(str(company_id), conversation_id))
        return True
    except Exception as e:
        logger.warning(f"Manager-action clear failed: {e}")
        return False
