"""Cross-turn memory for "the last specific date this conversation resolved
to" — e.g. after "4th Wednesday of August 2026" resolves to 2026-08-26, a
dateless follow-up like "yes, give me punch details" can use that date
instead of silently defaulting to today.

Short-TTL and single-use by design, same reasoning as bare_verb_clarify_
state.py / bare_date_clarify_state.py: this only needs to survive one
assistant-answer / user-follow-up round trip. Consumed (read + cleared) by
whichever date-driven node's OWN date resolution comes up empty for the
CURRENT message — a message that already names its own date never touches
this at all, since that always takes priority."""

import json
import os
import logging

from services.redis_chat_service import _get_redis

logger = logging.getLogger(__name__)

# Deliberately short: a stale entry here is actively harmful — the whole
# point is "the date we were JUST discussing", not a standing default. If
# the employee moves on to something unrelated later, this must not still
# be silently applied.
LAST_RESOLVED_DATE_TTL = int(os.getenv("LAST_RESOLVED_DATE_TTL", 300))  # 5 min


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


def set_last_resolved_date(company_id, conversation_id: str, date_iso: str) -> None:
    client = _get_redis()
    if not client:
        logger.warning("Redis unavailable — cannot remember last resolved date")
        return
    try:
        client.set(
            _key(str(company_id), conversation_id),
            json.dumps({"date": date_iso}),
            ex=LAST_RESOLVED_DATE_TTL,
        )
    except Exception as e:
        logger.warning(f"Redis last-resolved-date write failed: {e}")


def get_last_resolved_date(company_id, conversation_id: str):
    """Returns the ISO date string, or None."""
    client = _get_redis()
    if not client:
        return None
    try:
        raw = client.get(_key(str(company_id), conversation_id))
        return json.loads(raw)["date"] if raw else None
    except Exception as e:
        logger.warning(f"Redis last-resolved-date read failed: {e}")
        return None


def consume_last_resolved_date(company_id, conversation_id: str):
    """Reads the stored date and clears it in one step (single-use — see
    module docstring), or None if nothing was stored."""
    date_iso = get_last_resolved_date(company_id, conversation_id)
    if date_iso is not None:
        clear_last_resolved_date(company_id, conversation_id)
    return date_iso


def clear_last_resolved_date(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 last-resolved-date clear failed: {e}")
