#!/usr/bin/env python3
"""A deterministic, synthetic clean-merge failure. Requires Python 3 and Git.

Creates a disposable local repository with no remote or network access.
Both branches pass an existing shared invariant; their clean merge fails it.
No agent is run, and no production failure rate is measured.
"""

import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile


CHECK = '''import json
from pathlib import Path
east = json.loads(Path("east.json").read_text())["reserved"]
west = json.loads(Path("west.json").read_text())["reserved"]
total = east + west
print(f"reserved={total}, limit=100: {'PASS' if total <= 100 else 'FAIL'}")
raise SystemExit(0 if total <= 100 else 1)
'''


def main():
    env = os.environ.copy()
    # Keep machine-wide Git hooks, signing, templates, and identity out of the toy.
    for key in list(env):
        if key.startswith("GIT_"):
            del env[key]
    env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull,
               GIT_TERMINAL_PROMPT="0")
    with tempfile.TemporaryDirectory(prefix="clean-merge-demo-") as temp:
        repo = Path(temp)

        def git(*args):
            return subprocess.run(
                ["git", "-c", "user.name=Merge demo", "-c", "user.email=demo@example.invalid",
                 "-c", "commit.gpgsign=false", "-c", "core.hooksPath=/dev/null", *args],
                cwd=repo, env=env, check=True, text=True, capture_output=True,
            ).stdout.strip()

        def check(label, expected):
            result = subprocess.run([sys.executable, "check.py"], cwd=repo,
                                    text=True, capture_output=True)
            assert result.returncode == expected, result.stdout + result.stderr
            print(f"{label}: {result.stdout.strip()}")
            return {"label": label, "commit": git("rev-parse", "HEAD"),
                    "tree": git("rev-parse", "HEAD^{tree}"),
                    "exit_code": result.returncode}

        git("init", "--quiet", "--initial-branch=main", "--template=")
        (repo / "check.py").write_text(CHECK)
        for region in ("east", "west"):
            (repo / f"{region}.json").write_text(json.dumps({"reserved": 40}) + "\n")
        git("add", ".")
        git("commit", "--quiet", "-m", "Base configuration and invariant")
        base = git("rev-parse", "HEAD")
        results = [check("base", 0)]

        for region in ("east", "west"):
            git("switch", "--quiet", "--create", region, base)
            (repo / f"{region}.json").write_text(json.dumps({"reserved": 60}) + "\n")
            git("add", f"{region}.json")
            git("commit", "--quiet", "-m", f"Raise {region} reservation")
            results.append(check(region, 0))

        git("switch", "--quiet", "main")
        git("merge", "--quiet", "--ff-only", "east")
        git("merge", "--quiet", "--no-ff", "west", "-m", "Combine independent changes")
        assert git("ls-files", "--unmerged") == ""
        print("merge: CLEAN (Git exited 0; no unmerged index entries)")
        results.append(check("combined", 1))
        assert len({r["tree"] for r in results}) == 4
        assert git("status", "--porcelain") == ""
        print("Validated revisions:")
        print(json.dumps(results, indent=2))
        print("Expected integration failure reproduced; temporary repository removed on exit.")


if __name__ == "__main__":
    main()
