#!/usr/bin/env python3
"""Bump the minor version, test, build, upload, and tag a release."""

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


def release_version(bump):
    declarations = [
        (Path("setup.py"), r'(?m)^(\s*version=")(\d+\.\d+\.\d+)(",)$'),
        (Path("codex_continue/__init__.py"), r'(?m)^(__version__ = ")(\d+\.\d+\.\d+)(")$'),
        (Path("codex_continue/cli.py"), r'(?m)^(    __version__ = ")(\d+\.\d+\.\d+)(")$'),
    ]
    sources = []
    for path, pattern in declarations:
        source = path.read_text(encoding="utf-8")
        matches = list(re.finditer(pattern, source))
        if len(matches) != 1:
            raise ValueError(f"Expected one major.minor.patch version in {path}")
        sources.append((path, source, matches[0]))

    versions = {match.group(2) for _, _, match in sources}
    if len(versions) != 1:
        raise ValueError("Version declarations do not match; fix them before releasing.")
    version = versions.pop()
    if bump:
        major, minor, _ = map(int, version.split("."))
        version = f"{major}.{minor + 1}.0"
        for path, source, match in sources:
            path.write_text(
                source[:match.start(2)] + version + source[match.end(2):],
                encoding="utf-8",
            )
    return version


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--no-bump", action="store_true",
                        help="Use the current version (for retrying a failed release).")
    parser.add_argument("--no-upload", action="store_true",
                        help="Build and check without uploading.")
    args = parser.parse_args()

    os.chdir(Path(__file__).resolve().parent)
    python = os.environ.get("PYTHON") or sys.executable
    for command in (python, "pyproject-build", "twine", "git"):
        if shutil.which(command) is None:
            parser.exit(1, f"Required command not found: {command}\n")

    version = None
    uploaded = False
    try:
        if not args.no_upload:
            status = subprocess.run(
                ["git", "status", "--porcelain"], check=True, capture_output=True, text=True,
            ).stdout
            if status:
                raise ValueError("Commit or stash your changes before releasing so the tag matches the uploaded source.")
        subprocess.run([python, "-m", "unittest", "discover", "-v"], check=True)
        version = release_version(bump=not args.no_bump)
        tag = f"v{version}"
        if not args.no_upload:
            existing = subprocess.run(
                ["git", "tag", "--list", tag], check=True, capture_output=True, text=True,
            ).stdout.strip()
            if existing:
                raise ValueError(f"Tag {tag} already exists; choose a new release version.")
        print(f"Releasing {version}", flush=True)
        directory = f"dist/{version}"
        subprocess.run(["pyproject-build", "--outdir", directory], check=True)
        artifacts = [
            f"{directory}/codex_continue-{version}-py3-none-any.whl",
            f"{directory}/codex_continue-{version}.tar.gz",
        ]
        subprocess.run(["twine", "check", *artifacts], check=True)
        if args.no_upload:
            print(f"Artifacts ready in {directory} (not uploaded).")
        else:
            if not args.no_bump:
                subprocess.run(
                    ["git", "add", "--", "setup.py", "codex_continue/__init__.py", "codex_continue/cli.py"],
                    check=True,
                )
                subprocess.run(["git", "commit", "-m", f"Release {version}"], check=True)
            env = dict(os.environ)
            env["TWINE_USERNAME"] = env.get("TWINE_USERNAME") or "__token__"
            subprocess.run(["twine", "upload", *artifacts], check=True, env=env)
            uploaded = True
            subprocess.run(["git", "tag", "-a", tag, "-m", f"Release {version}"], check=True)
            print(f"Created local tag {tag}. Push it with: git push origin {tag}")
    except (OSError, ValueError, subprocess.CalledProcessError) as error:
        print(f"Release failed: {error}", file=sys.stderr)
        if uploaded:
            print(f"Upload succeeded. Create the tag with: git tag -a v{version} -m 'Release {version}'", file=sys.stderr)
        elif version is not None:
            print("Fix the error, commit any pending changes, and retry with --no-bump.", file=sys.stderr)
        return 1
    return 0


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