"""What the assistant has asked, and been told, about a policy it is drafting.

"Make me a policy" names a document and nothing else — not what it is about,
not what it has to cover. Writing one anyway produces a generic template
nobody asked for, so the flow asks first and this is where the answer waits
between the two turns.

Deliberately its own store rather than a field on an existing one: this has
nothing to do with the company's own policies (which live in the uploaded
documents and are READ, never written here), and nothing to do with the
leave-type/bare-verb clarifications, which resolve into a different flow.

Same Redis discipline as the other clarify stores in this package, including
the short TTL: a drafting brief is answered in the same conversational beat,
not resumed twenty minutes later against a question the user has forgotten.
Fails closed — with Redis unavailable the next turn is classified normally,
which costs the user a repeated question rather than a wrong answer.
"""
import json
import logging
import os

import redis

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
POLICY_DRAFT_STATE_TTL = 900


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 policy-draft-state store connected")
except Exception as e:
    logger.warning(f"Redis policy-draft-state store unavailable: {e} — a policy drafting brief won't survive the turn")
    _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 policy-draft-state store reconnected")
    except Exception:
        pass
    return _r


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


def get_state(company_id, conversation_id: str) -> dict | None:
    """The pending drafting brief, or None when nothing is in progress.

    Shape: {"step": "awaiting_brief", "subject": str|None, "asked": str}
      step     — always "awaiting_brief" today; named so a later step (a
                 revision round, say) can be told apart rather than guessed at.
      subject  — the policy's topic when the opening message already named it
                 ("a WFH policy"), so the follow-up question can ask only for
                 what is still missing instead of starting from nothing.
      asked    — the question actually put to the user, kept so the drafting
                 turn can see what its answer is an answer TO.
    """
    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"Policy-draft-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=POLICY_DRAFT_STATE_TTL)
        return True
    except Exception as e:
        logger.warning(f"Policy-draft-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"Policy-draft-state clear failed: {e}")
        return False
