#!/usr/bin/env python3
"""Release this library: one version, three places, one tag.

A release is a pair of numbers that must agree — the distribution version, the
`__version__` a running program reports, and the git tag a consumer pins. When
they drift, a findings document claims a library that never existed, and no
later tool can untangle which one was meant.

    tools/release patch          # 0.1.0 -> 0.1.1, tag v0.1.1
    tools/release minor          # 0.1.0 -> 0.2.0, tag v0.2.0
    tools/release 0.3.0          # explicit
    tools/release minor --dry-run

What it refuses, before touching anything:

  - a dirty working tree, untracked files included: a release that leaves half
    the work out is worse than no release;
  - a branch other than `main` (override with --branch): you tag what you push;
  - `origin/main` carrying commits you do not have: the tag would land on a
    commit that is about to be rewritten by a merge;
  - a tag that already exists, locally or on the remote. Tags are never moved —
    moving one silently changes what a past report was tested against.

What it does, in order: bump, refresh the lock, install, test, verify that the
three numbers agree, commit the bump, tag it. If the tests fail, the working
tree is restored and nothing is tagged.

It does not push. Publishing is the maintainer's decision: the last lines print
the push of the release commit and of that one tag, which is what
`.github/workflows/publish.yml` uploads to PyPI through Trusted Publishing —
no token is stored anywhere.
"""

from __future__ import annotations

import argparse
import re
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
PYPROJECT = ROOT / "pyproject.toml"
PACKAGE_INIT = ROOT / "src" / "perquisition" / "__init__.py"
TAG_PREFIX = "v"
PROJECT = "perquisition"

_VERSION_LINE = re.compile(r'(?m)^version = "([^"]+)"$')
_DUNDER_LINE = re.compile(r'(?m)^__version__ = "([^"]+)"$')
_SEMVER = re.compile(r"^(\d+)\.(\d+)\.(\d+)$")


class ReleaseError(RuntimeError):
    pass


def run(*args: str, check: bool = True) -> subprocess.CompletedProcess[str]:
    return subprocess.run(args, cwd=ROOT, text=True, capture_output=True, check=check)


def git(*args: str, check: bool = True) -> str:
    return run("git", *args, check=check).stdout.strip()


def version_of(path: Path, pattern: re.Pattern[str], what: str) -> str:
    text = path.read_text(encoding="utf-8")
    found = pattern.findall(text)
    if len(found) != 1:
        raise ReleaseError(f"{what}: expected exactly one version line in {path}, found {len(found)}")
    return found[0]


def next_version(current: str, part: str) -> str:
    if part.count(".") == 2:
        if not _SEMVER.match(part):
            raise ReleaseError(f"{part!r} is not MAJOR.MINOR.PATCH")
        return part
    if part not in ("major", "minor", "patch"):
        raise ReleaseError(f"{part!r}: expected major, minor, patch, or an explicit X.Y.Z")
    match = _SEMVER.match(current)
    if match is None:
        raise ReleaseError(f"current version {current!r} is not MAJOR.MINOR.PATCH")
    major, minor, patch = (int(n) for n in match.groups())
    if part == "major":
        return f"{major + 1}.0.0"
    if part == "minor":
        return f"{major}.{minor + 1}.0"
    return f"{major}.{minor}.{patch + 1}"


def preflight(branch: str) -> None:
    if git("rev-parse", "--is-inside-work-tree") != "true":
        raise ReleaseError(f"{ROOT} is not a git repository")

    dirty = git("status", "--porcelain=v1", "--untracked-files=normal")
    if dirty:
        raise ReleaseError(
            "the working tree is not clean, and a release must not decide what to leave out:\n  "
            + "\n  ".join(dirty.splitlines())
        )

    current_branch = git("rev-parse", "--abbrev-ref", "HEAD")
    if current_branch != branch:
        raise ReleaseError(
            f"on branch {current_branch!r}, not {branch!r}: you tag what you push. "
            f"If this is deliberate, pass --branch {current_branch}."
        )

    # A tag on a commit origin has already moved past would be a tag on the
    # wrong history. Network failures are not a reason to refuse a release.
    try:
        run("git", "fetch", "--quiet", "origin")
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("warning: could not reach origin; skipping the up-to-date check", file=sys.stderr)
        return
    upstream = run("git", "rev-parse", "--verify", "--quiet", f"origin/{branch}", check=False)
    if upstream.returncode != 0:
        return
    behind = run("git", "merge-base", "--is-ancestor", f"origin/{branch}", "HEAD", check=False)
    if behind.returncode != 0:
        raise ReleaseError(
            f"origin/{branch} has commits this checkout does not have: pull or merge first, "
            "or the tag lands on a history that is about to change"
        )


def refuse_existing_tag(tag: str) -> None:
    if run("git", "rev-parse", "--verify", "--quiet", f"refs/tags/{tag}", check=False).returncode == 0:
        raise ReleaseError(f"tag {tag} already exists locally; tags are never moved")
    remote = run("git", "ls-remote", "--tags", "origin", tag, check=False)
    if remote.returncode == 0 and remote.stdout.strip():
        raise ReleaseError(f"tag {tag} already exists on origin; a moved tag breaks every past report")


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("part", help="major, minor, patch, or an explicit X.Y.Z")
    parser.add_argument("--branch", default="main", help="branch a release may start from")
    parser.add_argument("--dry-run", action="store_true", help="say what would happen, change nothing")
    args = parser.parse_args(argv)

    try:
        preflight(args.branch)
        current = version_of(PYPROJECT, _VERSION_LINE, "pyproject.toml")
        reported = version_of(PACKAGE_INIT, _DUNDER_LINE, "__init__.py")
        if reported != current:
            raise ReleaseError(
                f"already inconsistent: pyproject says {current}, __version__ says {reported}. "
                "Fix that by hand first — this tool would otherwise bless the difference."
            )
        target = next_version(current, args.part)
        tag = f"{TAG_PREFIX}{target}"
        refuse_existing_tag(tag)
    except ReleaseError as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 1

    print(f"{PROJECT}: {current} -> {target} (tag {tag})")
    if args.dry_run:
        print("dry run: would bump, lock, install, test, commit and tag; nothing changed")
        return 0

    for path, pattern, template in (
        (PYPROJECT, _VERSION_LINE, 'version = "{v}"'),
        (PACKAGE_INIT, _DUNDER_LINE, '__version__ = "{v}"'),
    ):
        text = path.read_text(encoding="utf-8")
        path.write_text(pattern.sub(template.format(v=target), text, count=1), encoding="utf-8")

    try:
        run("uv", "lock")
        run("uv", "sync", "--locked")
        run("uv", "run", "pytest", "-q")
        # The three numbers are the point; assert them rather than hope.
        probe = (
            "import importlib.metadata as m, perquisition;"
            f"assert m.version({PROJECT!r}) == {target!r} == perquisition.__version__"
        )
        run("uv", "run", "python", "-c", probe)
    except subprocess.CalledProcessError as exc:
        run("git", "checkout", "--", str(PYPROJECT), str(PACKAGE_INIT), "uv.lock", check=False)
        output = (exc.stdout or "") + (exc.stderr or "")
        print(f"error: a gate failed, working tree restored, nothing tagged\n{output}", file=sys.stderr)
        return 1

    try:
        git("add", str(PYPROJECT), str(PACKAGE_INIT), "uv.lock")
        git("commit", "-m", f"release: {tag}")
        git("tag", "-a", tag, "-m", tag)
    except subprocess.CalledProcessError as exc:
        # A missing git identity, a hook, a full disk: leave the tree as we
        # found it rather than half-released.
        run("git", "reset", "--quiet", check=False)
        run("git", "checkout", "--", str(PYPROJECT), str(PACKAGE_INIT), "uv.lock", check=False)
        print(f"error: could not commit or tag, working tree restored\n{exc.stderr}", file=sys.stderr)
        return 1

    print(f"tagged {tag} at {git('rev-parse', '--short', 'HEAD')}")
    print(f"publish:  git push && git push origin {tag}")
    print(
        "          the tag push is the publish: .github/workflows/publish.yml"
        " re-runs the gates and uploads this version to PyPI. Push one tag,"
        " never --tags: every local release tag would upload its own version."
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
