"""Pending "did you mean <date>?" for punch details.

punch_details answers ONE day. "show my check-in before 9th sept" names a day
only as an anchor - the model read it as the 9th itself and showed that day's
punches, the one day the employee had just excluded. The node now resolves
the anchor, offers the day next to it ("Did you mean 8 Sep?"), and parks the
offer here so the next reply - "yes" or "no" - can be routed straight back to
punch_details by classify_node without an LLM call.

Short-TTL and single-use, same reasoning as bare_verb_clarify_state.py: it
only needs to survive one question/answer round trip, and a stale offer must
never catch a later, unrelated "yes".
"""

import json
import logging
import os
import re

from services.redis_chat_service import _get_redis

logger = logging.getLogger(__name__)

PUNCH_DATE_SUGGESTION_TTL = int(os.getenv("PUNCH_DATE_SUGGESTION_TTL", 300))  # 5 min

# Whole-reply answers only. Held letters are allowed ("yess", "okk", "noo").
_YES_RE = re.compile(
    r"^\s*(?:y+|ye+s+|yep|yeah+|ya+|yup|ok+(?:ay)?|k|sure|correct|right|confirm(?:ed)?|"
    r"go\s+ahead|proceed|please\s+do|do\s+it)"
    r"(?:\s+(?:please|pls|plz|show\s+(?:it|me|that)|go\s+ahead|proceed))?\s*[.!]*\s*$",
    re.IGNORECASE)
_NO_RE = re.compile(r"^\s*(?:n+o+|nope|nah|no\s+thanks?|not\s+that(?:\s+one)?|wrong)\s*[.!]*\s*$",
                    re.IGNORECASE)


def is_yes(reply: str) -> bool:
    return bool(_YES_RE.match(reply or ""))


def is_no(reply: str) -> bool:
    return bool(_NO_RE.match(reply or ""))


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


def set_state(company_id, conversation_id: str, date_iso: str) -> None:
    client = _get_redis()
    if not client:
        logger.warning("Redis unavailable — cannot remember the suggested punch date")
        return
    try:
        client.set(_key(str(company_id), conversation_id), json.dumps({"date": date_iso}),
                   ex=PUNCH_DATE_SUGGESTION_TTL)
    except Exception as e:
        logger.warning(f"Redis punch-date suggestion 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 punch-date suggestion 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 punch-date suggestion clear failed: {e}")
