"""
Checkpoint manager for resumable operations (scaffold).
"""

from __future__ import annotations

import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Optional


@dataclass
class CheckpointState:
    progress: int
    total: int
    last_cursor: Any


class OperationCheckpoint:
    def __init__(self, operation_id: str):
        self.state_file = Path(".g_gremlin") / "checkpoints" / f"{operation_id}.json"

    def save(self, progress: int, total: int, last_cursor: Any) -> None:
        self.state_file.parent.mkdir(parents=True, exist_ok=True)
        payload = {
            "progress": progress,
            "total": total,
            "last_cursor": last_cursor,
        }
        self.state_file.write_text(json.dumps(payload, indent=2), encoding="utf-8")

    def load(self) -> Optional[CheckpointState]:
        if not self.state_file.exists():
            return None
        try:
            data = json.loads(self.state_file.read_text(encoding="utf-8"))
            return CheckpointState(
                progress=data.get("progress", 0),
                total=data.get("total", 0),
                last_cursor=data.get("last_cursor"),
            )
        except Exception:
            return None

    def clear(self) -> None:
        if self.state_file.exists():
            self.state_file.unlink()
