"""utils/version_utils.py - version resolution helpers."""

from pathlib import Path

from accountable_record.boundary.toml import load_toml, require_table


def load_fallback_version(repo_dir: Path) -> str:
    """Load the stable fallback version from pyproject.toml."""
    pyproject_path = repo_dir / "pyproject.toml"

    if not pyproject_path.exists():
        msg = f"Missing pyproject.toml: {pyproject_path}"
        raise FileNotFoundError(msg)

    data = load_toml(pyproject_path)

    tool = require_table(data, "tool", "pyproject.toml")
    hatch = require_table(tool, "hatch", "[tool.hatch]")
    version_table = require_table(hatch, "version", "[tool.hatch.version]")

    version = version_table.get("fallback-version")
    if not isinstance(version, str) or not version.strip():
        msg = "[tool.hatch.version] fallback-version must be a non-empty string."
        raise ValueError(msg)

    return version.strip()
