"""Persistence for the currently active project."""

__author__ = "Lene Preuss <lene.preuss@gmail.com>"

import json
from pathlib import Path

from stable_delusion.project.xdg_paths import data_dir

_ACTIVE_PROJECT_FILENAME = "active_project.json"


def _active_file() -> Path:
    return data_dir() / _ACTIVE_PROJECT_FILENAME


def set_active_project(name: str, project_dir: Path) -> None:
    """Persist the active project name and path to XDG data dir."""
    _active_file().parent.mkdir(parents=True, exist_ok=True)
    _active_file().write_text(
        json.dumps({"name": name, "path": str(project_dir)}), encoding="utf-8"
    )


def get_active_project() -> tuple[str, Path] | None:
    """Return (name, path) of the active project, or None if not set."""
    f = _active_file()
    if not f.exists():
        return None
    data = json.loads(f.read_text(encoding="utf-8"))
    return data["name"], Path(data["path"])


def clear_active_project() -> None:
    """Remove the active project file if it exists."""
    f = _active_file()
    if f.exists():
        f.unlink()
