#!/usr/bin/env python3
"""Work out and stamp tangier's release version. The git tags hold it, not the source.

Usage:
  bin/release-version next <patch|minor|major|X.Y.Z>
  bin/release-version stamp <X.Y.Z>

`next` bumps the highest plain `vX.Y.Z` tag, and refuses when HEAD is already
released. It prints `version=X.Y.Z` and `previous=A.B.C` in the form
`$GITHUB_OUTPUT` takes. `stamp` writes the version into `pyproject.toml` and
`tangier/__init__.py` for the build, which never commits it.
Both run in the repo root. .github/workflows/release.yaml runs them.
"""

import re
import subprocess
import sys

PLAIN = re.compile(r"^(\d+)\.(\d+)\.(\d+)$")

# Each file, and how it names the version.
FILES = {
    "pyproject.toml": re.compile(r'^(version = )"[^"]*"$', re.M),
    "tangier/__init__.py": re.compile(r'^(__version__ = )"[^"]*"$', re.M),
}


def parse(version: str) -> tuple[int, int, int] | None:
    """The version as a sort key, or None when it is not plain X.Y.Z."""
    match = PLAIN.match(version)
    if not match:
        return None
    major, minor, patch = (int(part) for part in match.groups())
    return major, minor, patch


def require_plain(version: str) -> tuple[int, int, int]:
    # Plain X.Y.Z only: a pre-release would move the `@v0` alias onto an rc.
    key = parse(version)
    if key is None:
        sys.exit(f"error: version must look like 1.2.3, got: {version}")
    return key


def git_tags(*args: str) -> list[str]:
    out = subprocess.run(["git", "tag", "-l", *args, "v*"], capture_output=True, text=True, check=True).stdout
    return [tag for tag in out.split() if parse(tag[1:])]


def next_version(bump: str) -> None:
    released = git_tags("--points-at", "HEAD")
    if released:
        sys.exit(f"error: HEAD is already released as {released[0]}")
    previous = max((tag[1:] for tag in git_tags()), key=require_plain, default="")
    major, minor, patch = require_plain(previous) if previous else (0, 0, 0)
    if bump == "patch":
        version = f"{major}.{minor}.{patch + 1}"
    elif bump == "minor":
        version = f"{major}.{minor + 1}.0"
    elif bump == "major":
        version = f"{major + 1}.0.0"
    elif require_plain(bump) <= (major, minor, patch):
        sys.exit(f"error: {bump} is not above the highest release {previous or '0.0.0'}")
    else:
        version = bump
    print(f"version={version}")
    print(f"previous={previous}")


def stamp(version: str) -> None:
    _ = require_plain(version)
    rewritten = {}
    for path, pattern in FILES.items():
        with open(path) as fh:
            text = fh.read()
        new, count = pattern.subn(rf'\1"{version}"', text)
        if count != 1:
            sys.exit(f"error: {path} names a version {count} times, expected once")
        rewritten[path] = new
    for path, text in rewritten.items():
        with open(path, "w") as fh:
            _ = fh.write(text)


def main(argv: list[str]) -> None:
    if len(argv) != 2 or argv[0] not in ("next", "stamp"):
        sys.exit(__doc__.split("\n\n")[1])
    if argv[0] == "next":
        next_version(argv[1])
    else:
        stamp(argv[1])


if __name__ == "__main__":
    main(sys.argv[1:])
