"""In-memory store for pending destructive operations.

Saves pending selections and executions with 5-minute TTL.
State is per-process and lost on restart (acceptable for ephemeral ops).
"""

from __future__ import annotations

import logging
import time
from typing import Any

logger = logging.getLogger(__name__)

__all__ = [
    "clear_pending",
    "get_pending",
    "save_pending_execution",
    "save_pending_selection",
]

EXPIRY_SECONDS: int = 300  # 5 minutes

_pending: dict[str, dict[str, Any]] = {}


def save_pending_selection(
    user_id: str,
    intent: str,
    transactions: list[Any],
    confirmation_text: str,
    edit_params: dict[str, Any] | None = None,
) -> None:
    """Save a pending selection when search returned results awaiting user choice.

    Args:
        user_id: User identifier.
        intent: The user's intent (delete, edit, etc.).
        transactions: List of candidate transactions.
        confirmation_text: Text to show user for confirmation.
        edit_params: Optional parameters for edit operations.
    """
    _pending[user_id] = {
        "type": "selection",
        "intent": intent,
        "transactions": transactions,
        "confirmation_text": confirmation_text,
        "edit_params": edit_params,
        "timestamp": time.time(),
    }
    logger.info(
        "pending_selection saved: user=%s, intent=%s, count=%d",
        user_id,
        intent,
        len(transactions),
    )


def save_pending_execution(
    user_id: str,
    tool_calls: list[Any],
    search_result: str,
    confirmation_text: str,
) -> None:
    """Save a pending execution when a destructive op was blocked.

    Args:
        user_id: User identifier.
        tool_calls: Blocked tool calls.
        search_result: Context from the search.
        confirmation_text: Text to show user for confirmation.
    """
    _pending[user_id] = {
        "type": "execution",
        "tool_calls": tool_calls,
        "search_result": search_result,
        "confirmation_text": confirmation_text,
        "timestamp": time.time(),
    }
    logger.info("pending_execution saved: user=%s", user_id)


def get_pending(user_id: str) -> dict[str, Any] | None:
    """Get pending operation if it exists and hasn't expired.

    Args:
        user_id: User identifier.

    Returns:
        Pending operation dict, or None if expired/absent.
    """
    op = _pending.get(user_id)
    if not op:
        return None
    if time.time() - op["timestamp"] > EXPIRY_SECONDS:
        logger.info("pending_op expired: user=%s", user_id)
        del _pending[user_id]
        return None
    return op


def clear_pending(user_id: str) -> None:
    """Remove pending operation after execution or cancellation.

    Args:
        user_id: User identifier.
    """
    if user_id in _pending:
        del _pending[user_id]
        logger.info("pending_op cleared: user=%s", user_id)
