"""Progress tracking — load, save, and reset user progress."""

from __future__ import annotations

import json
from pathlib import Path

from cde_onboard.constants import PROGRESS_FILE
from cde_onboard.models import ProgressData


class ProgressManager:
    """Manages persistent lesson progress stored as JSON."""

    def __init__(self, path: Path | None = None) -> None:
        self._path = path or PROGRESS_FILE
        self._data: ProgressData | None = None

    @property
    def data(self) -> ProgressData:
        """Lazy-load progress data."""
        if self._data is None:
            self._data = self._load()
        return self._data

    def _load(self) -> ProgressData:
        """Load progress from disk, returning empty progress if not found."""
        if self._path.exists():
            try:
                raw = json.loads(self._path.read_text(encoding="utf-8"))
                return ProgressData.model_validate(raw)
            except (json.JSONDecodeError, ValueError, KeyError):
                return ProgressData()
        return ProgressData()

    def save(self) -> None:
        """Persist current progress to disk."""
        self._path.parent.mkdir(parents=True, exist_ok=True)
        self._path.write_text(
            self.data.model_dump_json(indent=2),
            encoding="utf-8",
        )

    def mark_completed(self, lesson_id: str) -> None:
        """Mark a lesson as completed and save."""
        self.data.mark_completed(lesson_id)
        self.save()

    def is_completed(self, lesson_id: str) -> bool:
        """Check if a lesson has been completed."""
        return self.data.is_completed(lesson_id)

    def reset(self) -> None:
        """Clear all progress."""
        self._data = ProgressData()
        if self._path.exists():
            self._path.unlink()
        # Also remove the directory if empty
        progress_dir = self._path.parent
        if progress_dir.exists() and not any(progress_dir.iterdir()):
            progress_dir.rmdir()
