from __future__ import annotations

from typing import Any

from nexus.core.state.diff_engine import DiffEngine, DiffRecord


class TimeTravelDebugger:
    """Applies and rewinds state using diff records."""

    def __init__(self) -> None:
        self._engine = DiffEngine()

    def replay(self, base: dict[str, Any], diffs: list[DiffRecord]) -> dict[str, Any]:
        """Replay diffs forward over base state."""
        state = dict(base)
        for diff in diffs:
            state = self._engine.apply(state, diff)
        return state

    def rewind(self, current: dict[str, Any], diffs: list[DiffRecord]) -> dict[str, Any]:
        """Rewind state by applying inverted diffs in reverse order."""
        state = dict(current)
        for diff in reversed(diffs):
            state = self._engine.apply(state, self._engine.invert(diff))
        return state
