"""At-most-once submission of a confirmed apply-leave draft.

Two "yes" replies to the same card, sent at once (a double tap, two tabs),
each load the draft at the start of their turn and each called
erp_client.apply_leave: two identical leave requests reached the approver
(negative run, 28 Oct 2026, #37). The chat in-flight lock that would
serialise them ships off (chat_inflight.CHAT_INFLIGHT_ENABLED), so the submit
claims the draft itself, right before the erp call.

Keyed by the draft's identity, not just the conversation: a NEW request in
the same chat is never blocked by the last one. Kept after a success until
the TTL - releasing it then would let the slower duplicate, which already
holds a copy of the draft, claim it a moment later. Released on failure so
the existing "please try again" replies still work.

Its own module, not part of leave_slot_service, because tests replace that
module wholesale with fakes that know nothing about claims; it shares that
module's Redis client.
"""
import logging
import threading
import time

from services import leave_slot_service

logger = logging.getLogger(__name__)

SUBMIT_CLAIM_TTL = 120
_claims: dict = {}
_claims_lock = threading.Lock()


def _claim_key(company_id, conversation_id: str, fingerprint) -> str:
    return f"leave_submit:{company_id}:{conversation_id}:" + "|".join(str(p) for p in fingerprint)


def claim(company_id, conversation_id: str, fingerprint) -> bool:
    """True when this turn may submit the draft `fingerprint` identifies;
    False when another turn already has. In-process first (atomic between
    turns on one worker), then Redis SET NX across workers; a Redis that
    cannot answer leaves the in-process result standing."""
    key = _claim_key(company_id, conversation_id, fingerprint)
    now = time.monotonic()
    with _claims_lock:
        held_until = _claims.get(key)
        if held_until is not None and held_until > now:
            return False
        _claims[key] = now + SUBMIT_CLAIM_TTL
    client = leave_slot_service._get_redis()
    if not client:
        return True
    try:
        if client.set(key, "1", nx=True, ex=SUBMIT_CLAIM_TTL):
            return True
    except Exception as e:
        logger.warning(f"Leave submit claim failed: {e} — in-process claim only")
        return True
    with _claims_lock:
        _claims.pop(key, None)
    return False


def release(company_id, conversation_id: str, fingerprint) -> None:
    key = _claim_key(company_id, conversation_id, fingerprint)
    with _claims_lock:
        _claims.pop(key, None)
    client = leave_slot_service._get_redis()
    if not client:
        return
    try:
        client.delete(key)
    except Exception as e:
        logger.warning(f"Leave submit release failed: {e}")
