"""
Robot Framework library for checkpoint/resume support.

Loaded into .robot files to allow steps to check if they should be skipped
(already completed in a previous execution) and to retrieve idempotency keys
from previous runs.

Usage in .robot:
  Library    checkpoint_library.py    completed_steps=${COMPLETED_STEPS}

  *** Tasks ***
  My Step
      ${skip}=    Should Skip    my_step_id
      IF    ${skip}
          Log    Skipping (already completed)
          RETURN
      END
      # ... actual automation logic ...
"""


class checkpoint_library:
    """Checkpoint/resume support for Robot Framework desktop automations."""

    ROBOT_LIBRARY_SCOPE = "GLOBAL"

    def __init__(self, completed_steps: str = ""):
        """
        Args:
            completed_steps: Comma-separated list of step IDs that were
                           already completed in a previous execution.
        """
        self._completed = set(
            s.strip() for s in completed_steps.split(",") if s.strip()
        )
        self._idempotency_keys = {}

    def should_skip(self, step_id: str) -> bool:
        """Check if a step should be skipped (already completed).

        Args:
            step_id: The unique identifier of the step.

        Returns:
            True if the step was already completed and should be skipped.
        """
        return step_id in self._completed

    def get_completed_steps(self) -> list:
        """Return the list of completed step IDs."""
        return sorted(self._completed)

    def set_idempotency_key(self, step_id: str, key: str):
        """Store an idempotency key for a step.

        Call this after a side-effect step completes (e.g., after paying a tax,
        store the payment confirmation number).

        Args:
            step_id: The step that produced this key.
            key: The idempotency value (e.g., invoice number, payment ID).
        """
        self._idempotency_keys[step_id] = key

    def get_idempotency_key(self, step_id: str) -> str:
        """Retrieve the idempotency key for a step.

        Args:
            step_id: The step to look up.

        Returns:
            The idempotency key, or empty string if not set.
        """
        return self._idempotency_keys.get(step_id, "")

    def mark_completed(self, step_id: str):
        """Manually mark a step as completed (for dynamic step management).

        Args:
            step_id: The step to mark as completed.
        """
        self._completed.add(step_id)
