import json
from pathlib import Path

from unmake import HistoryManager, OperationRegistry, SQLiteStorage


class RestoreFile:
    def __init__(self, payload: dict[str, str]):
        self.path = Path(payload["path"])
        self.original = payload["original"]

    def undo(self) -> None:
        self.path.write_text(self.original, encoding="utf-8")


config_path = Path("settings.json")
if not config_path.exists():
    config_path.write_text(json.dumps({"debug": False}), encoding="utf-8")

manager = HistoryManager(SQLiteStorage("example.db"))
registry = OperationRegistry()
registry.register("config.restore", RestoreFile)

with manager.start_session(script="configuration_update.py") as session:
    original = config_path.read_text(encoding="utf-8")
    data = json.loads(original)
    data["debug"] = True
    config_path.write_text(json.dumps(data), encoding="utf-8")
    session.record_operation("config.restore", {"path": str(config_path), "original": original})

manager.undo_session(manager.list_sessions(limit=1)[0].session_id, registry)
