#!/usr/bin/env scripts/uv-run-script
# -*- mode: python -*-
# /// script
# requires-python = ">=3.9"
# dependencies = ["packaging"]
# ///
"""Verify that the version in pyproject.toml is PEP 440 compliant.

Performs the following validation:
- Ensures version in pyproject.toml is PEP 440 compliant (e.g., "4.1.0.dev0" not "4.1.0.dev")

Usage:
    scripts/verify-package-version       # Check version compliance (exit 0 if OK, 1 if not compliant)
"""

import sys
from pathlib import Path

from packaging.version import InvalidVersion
from packaging.version import Version

try:
    import tomllib
except ModuleNotFoundError:
    import tomli as tomllib  # type: ignore[import-not-found]


def is_pep440_compliant(version_str: str) -> tuple[bool, str]:
    """Check if a version string is strictly PEP 440 compliant.

    Returns:
        Tuple of (is_compliant, normalized_version)
    """
    try:
        parsed = Version(version_str)
        normalized = str(parsed)

        # Check if the original matches the normalized form
        # If they differ, the version had implicit defaults which is not strictly compliant
        is_compliant = version_str == normalized
        return is_compliant, normalized
    except InvalidVersion:
        return False, ""


def read_pyproject_version(pyproject_path: Path) -> str:
    """Read version from pyproject.toml."""
    with open(pyproject_path, "rb") as f:
        data = tomllib.load(f)
    return data["project"]["version"]


def main() -> int:
    """Main entry point."""
    repo_root = Path(__file__).parent.parent
    pyproject_path = repo_root / "pyproject.toml"

    try:
        pyproject_version = read_pyproject_version(pyproject_path)

        # Check PEP 440 compliance
        is_compliant, normalized_version = is_pep440_compliant(pyproject_version)
        if not is_compliant:
            print(f"✗ Version in pyproject.toml is not PEP 440 compliant: {pyproject_version}", file=sys.stderr)
            print(f"  PEP 440 requires explicit numbers for pre-release, post, and dev versions", file=sys.stderr)
            print(f"  Suggested fix: {normalized_version}", file=sys.stderr)
            return 1

        print(f"✓ Version {pyproject_version} is PEP 440 compliant")
        return 0

    except Exception as e:
        print(f"✗ Error: {e}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
