"""Pending-clarification state for bare/ambiguous verb queries (e.g. 'apply',
'cancel', 'regularise', 'check') that carry no object to anchor intent on.
Short-TTL by design — this only needs to survive one assistant-question /
user-answer round trip, unlike chat history."""

import json
import os
import logging

# TODO: confirm actual module path/filename for the pasted redis client file
from services.redis_chat_service import _get_redis

logger = logging.getLogger(__name__)

# Deliberately short: a stale entry here is actively harmful. If the user
# comes back much later and says something unrelated, it must NOT be
# silently resolved against a long-abandoned "apply".
BARE_VERB_CLARIFY_TTL = int(os.getenv("BARE_VERB_CLARIFY_TTL", 300))  # 5 min


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


def set_state(company_id, conversation_id: str, verb: str) -> None:
    client = _get_redis()
    if not client:
        # Fail open: caller must treat a failed set() as "skip the clarify
        # fast-path" rather than asking a question it can't later resolve.
        logger.warning("Redis unavailable — cannot set bare-verb clarify state")
        return
    try:
        client.set(
            _key(str(company_id), conversation_id),
            json.dumps({"verb": verb}),
            ex=BARE_VERB_CLARIFY_TTL,
        )
    except Exception as e:
        logger.warning(f"Redis bare-verb clarify write failed: {e}")


def get_state(company_id, conversation_id: str):
    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"Redis bare-verb clarify read failed: {e}")
        return None


def clear_state(company_id, conversation_id: str) -> None:
    client = _get_redis()
    if not client:
        return
    try:
        client.delete(_key(str(company_id), conversation_id))
    except Exception as e:
        logger.warning(f"Redis bare-verb clarify clear failed: {e}")