#!/usr/bin/env python3
"""Pre-push hook: auto-bump patch version in both packages when pushing to main."""
import re
import subprocess
import sys
from pathlib import Path

MCP_TOML = "stratum-mcp/pyproject.toml"
PY_TOML = "pyproject.toml"


def read_version(path: str) -> str | None:
    m = re.search(r'^version = "(\d+\.\d+\.\d+)"', Path(path).read_text(), re.MULTILINE)
    return m.group(1) if m else None


def bump_patch(version: str) -> str:
    major, minor, patch = version.split(".")
    return f"{major}.{minor}.{int(patch) + 1}"


def set_version(path: str, old: str, new: str) -> None:
    p = Path(path)
    p.write_text(p.read_text().replace(f'version = "{old}"', f'version = "{new}"', 1))


# Only bump when pushing to main
ZERO = "0" * 40
main_local = main_remote = None
for line in sys.stdin.read().splitlines():
    parts = line.strip().split()
    if len(parts) >= 4 and parts[2] in ("refs/heads/main", "main"):
        main_local, main_remote = parts[1], parts[3]
        break

if main_local is None:
    sys.exit(0)

# Loop guard: this hook creates a commit, but a commit made during pre-push
# can never be part of the push that triggered it — so it lands unpushed and
# the next push re-triggers the hook forever. Break the cycle: if every commit
# being pushed to main is already a `chore: bump` commit (i.e. nothing real
# changed since the last bump), do not bump again.
if main_remote and ZERO not in (main_remote, main_local):
    try:
        out = subprocess.run(
            ["git", "log", "--format=%s", f"{main_remote}..{main_local}"],
            capture_output=True, text=True, check=True,
        ).stdout
        subjects = [s for s in out.splitlines() if s.strip()]
        if subjects and all(s.startswith("chore: bump to ") for s in subjects):
            print("pre-push: only bump commits pending — skipping bump (loop guard)")
            sys.exit(0)
    except subprocess.CalledProcessError:
        pass  # safe default: fall through and bump as before

current = read_version(MCP_TOML)
if not current:
    print("pre-push: could not read version from stratum-mcp/pyproject.toml", file=sys.stderr)
    sys.exit(1)

new_version = bump_patch(current)
print(f"pre-push: {current} → {new_version}")

set_version(MCP_TOML, current, new_version)
set_version(PY_TOML, current, new_version)

subprocess.run(["git", "add", MCP_TOML, PY_TOML], check=True)
subprocess.run(["git", "commit", "-m", f"chore: bump to {new_version}"], check=True)
