#!/usr/bin/env python3
# retoor <retoor@molodetz.nl>

import re
import subprocess
import sys
from pathlib import Path

REPO_ROOT = Path(
    subprocess.run(
        ["git", "rev-parse", "--show-toplevel"],
        capture_output=True,
        text=True,
        check=True,
    ).stdout.strip()
)
PYPROJECT = REPO_ROOT / "pyproject.toml"
VERSION_LINE = re.compile(r'^version = "(\d+)\.(\d+)\.(\d+)"$', re.MULTILINE)
STAGED_VERSION_CHANGE = re.compile(r'^[+-]version = "\d+\.\d+\.\d+"$', re.MULTILINE)


def staged_diff(path: Path) -> str:
    result = subprocess.run(
        ["git", "diff", "--cached", "--unified=0", "--", str(path)],
        capture_output=True,
        text=True,
        cwd=REPO_ROOT,
    )
    return result.stdout


def main() -> int:
    if (REPO_ROOT / ".git" / "MERGE_HEAD").exists():
        return 0
    if not PYPROJECT.is_file():
        return 0
    if STAGED_VERSION_CHANGE.search(staged_diff(PYPROJECT)):
        return 0
    text = PYPROJECT.read_text()
    match = VERSION_LINE.search(text)
    if not match:
        return 0
    major, minor, patch = (int(part) for part in match.groups())
    bumped = f'version = "{major}.{minor}.{patch + 1}"'
    PYPROJECT.write_text(VERSION_LINE.sub(bumped, text, count=1))
    subprocess.run(["git", "add", str(PYPROJECT)], cwd=REPO_ROOT, check=True)
    return 0


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