"""Shared version management utilities for build scripts.

This module provides a single source of truth for version reading
to avoid duplication between different build scripts.
"""

import re
from pathlib import Path


def get_project_root() -> Path:
    """Get the project root directory.

    Returns:
        Path to project root (parent of build/scripts)
    """
    return Path(__file__).parent.parent.parent


def get_current_version() -> str:
    """Read version from __init__.py.

    This is the single source of truth for version information.
    All build scripts and version management tools use this function.

    Returns:
        Current version string from __init__.py

    Raises:
        ValueError: If __version__ cannot be found in __init__.py
    """
    project_root = get_project_root()
    init_file = project_root / "src" / "webdrop_bridge" / "__init__.py"

    if not init_file.exists():
        raise FileNotFoundError(
            f"Cannot find __init__.py at {init_file}"
        )

    content = init_file.read_text(encoding="utf-8")
    match = re.search(r'__version__\s*=\s*["\']([^"\']+)["\']', content)

    if not match:
        raise ValueError(
            f"Could not find __version__ in {init_file}. "
            "Expected: __version__ = \"X.Y.Z\""
        )

    return match.group(1)
