#!/usr/bin/env python3
"""Reproduce Git ignore/index behavior in disposable local repositories.

Requires Python 3.9+ and Git on PATH. Prints JSON to stdout.
Creates repositories only inside an automatically removed temporary directory;
uses no network, real project files, global Git writes, or credentials.
"""

import json
import os
from pathlib import Path
import platform
import shutil
import subprocess
import tempfile


TARGET = "local-settings.txt"
V1 = "mode=demo-v1\n"
V2 = "mode=demo-v2\n"
V3 = "mode=demo-v3\n"


def require(condition, message):
    if not condition:
        raise RuntimeError(message)


def run_lab():
    executable = shutil.which("git")
    if executable is None:
        raise RuntimeError("Git must be installed and available on PATH")
    env = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")}
    env.update({
        "GIT_CONFIG_NOSYSTEM": "1",
        "GIT_CONFIG_GLOBAL": os.devnull,
        "GIT_TERMINAL_PROMPT": "0",
        "GIT_AUTHOR_DATE": "2026-10-22T20:00:00+08:00",
        "GIT_COMMITTER_DATE": "2026-10-22T20:00:00+08:00",
        "LC_ALL": "C",
    })
    config = ["-c", "user.name=Gumi Lab", "-c", "user.email=lab@example.invalid",
              "-c", "commit.gpgsign=false", "-c", "core.hooksPath=" + os.devnull,
              "-c", "core.autocrlf=false", "-c", "color.ui=false"]
    trace = []
    cases = []
    with tempfile.TemporaryDirectory(prefix="gumi-gitignore-index-") as temp:
        root = Path(temp)

        def git(repo, *args, expected=0):
            result = subprocess.run([executable, *config, *args], cwd=repo, env=env,
                                    text=True, capture_output=True)
            clean = lambda text: text.replace(str(root), "<lab>")
            trace.append({"repository": str(repo.relative_to(root)) or ".",
                          "arguments": [clean(arg) for arg in args],
                          "exit_code": result.returncode,
                          "stdout": clean(result.stdout), "stderr": clean(result.stderr)})
            require(result.returncode == expected,
                    "unexpected Git exit: " + repr(trace[-1]))
            return result.stdout

        def new_repo(name):
            repo = root / name
            repo.mkdir()
            git(repo, "init", "-q", "--initial-branch=main")
            (repo / "README.txt").write_text("Disposable Gumi demonstration.\n", encoding="utf-8")
            git(repo, "add", "--", "README.txt")
            git(repo, "commit", "-qm", "Initialize demonstration")
            return repo

        def write(repo, name, text):
            path = repo / name
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_text(text, encoding="utf-8")

        work = new_repo("work")
        write(work, TARGET, V1)
        git(work, "add", "--", TARGET)
        git(work, "commit", "-qm", "Track sample settings")
        git(root, "clone", "-q", str(work), "clean-peer")
        git(root, "clone", "-q", str(work), "modified-peer")
        peer = root / "clean-peer"
        modified = root / "modified-peer"
        write(modified, TARGET, "mode=peer-local\n")

        write(work, ".gitignore", TARGET + "\n")
        git(work, "add", "--", ".gitignore")
        git(work, "commit", "-qm", "Ignore future local settings")
        write(work, TARGET, V2)
        changed = git(work, "status", "--short", "--", TARGET)
        tracked = git(work, "ls-files", "--error-unmatch", "--", TARGET)
        no_match_output = git(work, "check-ignore", "-v", "--", TARGET, expected=1)
        rule = git(work, "check-ignore", "-v", "--no-index", "--", TARGET)
        indexed_and_matching = git(work, "ls-files", "-ci", "--exclude-standard", "--", TARGET)
        require(changed == " M " + TARGET + "\n", "tracked modification must remain visible")
        require(tracked == TARGET + "\n" and indexed_and_matching == tracked, "index query mismatch")
        require(no_match_output == "" and rule == ".gitignore:1:" + TARGET + "\t" + TARGET + "\n",
                "check-ignore comparison mismatch")
        git(work, "add", "--", TARGET)
        staged = git(work, "status", "--short", "--", TARGET)
        require(staged == "M  " + TARGET + "\n", "tracked add must stage modification")
        git(work, "restore", "--staged", "--", TARGET)
        require((work / TARGET).read_text() == V2, "unstaging changed local content")
        cases.append({"case": "tracked_file_with_matching_ignore", "status_before_add": changed,
                      "ls_files": tracked, "default_check_ignore_exit": 1,
                      "default_check_ignore_stdout": no_match_output, "no_index_rule": rule,
                      "tracked_matching_rule": indexed_and_matching, "status_after_add": staged})

        git(work, "rm", "--cached", "--", TARGET)
        removal = git(work, "diff", "--cached", "--name-status", "--", TARGET)
        require(removal == "D\t" + TARGET + "\n" and (work / TARGET).read_text() == V2,
                "cached removal did not preserve working file")
        git(work, "restore", "--staged", "--", TARGET)
        undo_status = git(work, "status", "--short", "--", TARGET)
        require(undo_status == " M " + TARGET + "\n" and (work / TARGET).read_text() == V2,
                "staged removal undo failed")
        git(work, "rm", "--cached", "--", TARGET)
        git(work, "commit", "-qm", "Stop tracking local settings")
        ignored = git(work, "status", "--short", "--ignored", "--", TARGET)
        ordinary = git(work, "status", "--short", "--", TARGET)
        old_content = git(work, "show", "HEAD~1:" + TARGET)
        git(work, "ls-files", "--error-unmatch", "--", TARGET, expected=1)
        require(ordinary == "" and ignored == "!! " + TARGET + "\n", "local file must now be ignored")
        require((work / TARGET).read_text() == V2 and old_content == V1, "local/history data mismatch")
        cases.append({"case": "cached_removal_and_undo", "staged_name_status": removal,
                      "status_after_undo": undo_status, "local_content_after_commit": V2,
                      "ordinary_status_after_commit": ordinary, "ignored_status_after_commit": ignored,
                      "previous_commit_content": old_content})

        git(peer, "fetch", "-q", "origin")
        git(peer, "merge", "--ff-only", "origin/main")
        require(not (peer / TARGET).exists() and (peer / ".gitignore").read_text() == TARGET + "\n",
                "clean peer must apply committed deletion")
        require(git(peer, "status", "--porcelain") == "", "clean peer must stay clean")
        cases.append({"case": "clean_clone_fast_forward", "file_exists_after_update": False,
                      "ignore_rule_received": True, "working_tree_clean": True})

        before = git(modified, "rev-parse", "HEAD")
        git(modified, "fetch", "-q", "origin")
        git(modified, "merge", "--ff-only", "origin/main", expected=1)
        after = git(modified, "rev-parse", "HEAD")
        require(before == after and (modified / TARGET).read_text() == "mode=peer-local\n",
                "refused update must preserve peer HEAD and modified file")
        cases.append({"case": "modified_clone_fast_forward", "merge_exit": 1,
                      "head_unchanged": True, "preserved_content": "mode=peer-local\n"})

        staged_only = new_repo("staged-only")
        write(staged_only, TARGET, V1)
        git(staged_only, "add", "--", TARGET)
        write(staged_only, ".gitignore", TARGET + "\n")
        added = git(staged_only, "status", "--short", "--", TARGET)
        require(added == "A  " + TARGET + "\n", "uncommitted index entry was ignored unexpectedly")
        git(staged_only, "restore", "--staged", "--", TARGET)
        untracked_ignored = git(staged_only, "status", "--short", "--ignored", "--", TARGET)
        require(untracked_ignored == "!! " + TARGET + "\n" and (staged_only / TARGET).read_text() == V1,
                "unstaging new file must leave ignored working copy")
        cases.append({"case": "staged_but_never_committed", "before_unstage": added,
                      "after_unstage": untracked_ignored, "working_file_preserved": True,
                      "ignore_file_committed": False})

        force = new_repo("force-add")
        write(force, ".gitignore", TARGET + "\n")
        write(force, TARGET, V1)
        git(force, "add", "--", ".gitignore")
        git(force, "commit", "-qm", "Add ignore rule")
        git(force, "add", "--", TARGET, expected=1)
        require(git(force, "ls-files", "--", TARGET) == "", "ordinary add must not add ignored file")
        git(force, "add", "-f", "--", TARGET)
        forced = git(force, "status", "--short", "--", TARGET)
        require(forced == "A  " + TARGET + "\n", "force add did not create index entry")
        cases.append({"case": "explicit_add_and_force", "ordinary_add_exit": 1,
                      "forced_add_exit": 0, "status_after_force": forced})

        divergent = new_repo("divergent-index")
        write(divergent, TARGET, V1)
        git(divergent, "add", "--", TARGET)
        git(divergent, "commit", "-qm", "Track boundary sample")
        write(divergent, TARGET, V2)
        git(divergent, "add", "--", TARGET)
        write(divergent, TARGET, V3)
        git(divergent, "rm", "--cached", "--", TARGET, expected=1)
        indexed = git(divergent, "show", ":" + TARGET)
        disk = (divergent / TARGET).read_text()
        require(indexed == V2 and disk == V3, "refused rm must preserve both distinct contents")
        cases.append({"case": "divergent_index_cached_removal", "rm_exit": 1,
                      "preserved_index_content": indexed, "preserved_working_content": disk})

        patterns = new_repo("parent-negation")
        write(patterns, "cache/keep.txt", "keep demonstration\n")
        write(patterns, "cache/discard.txt", "discard demonstration\n")
        write(patterns, ".gitignore", "cache/\n!cache/keep.txt\n")
        parent_rule = git(patterns, "check-ignore", "-v", "--", "cache/keep.txt")
        require(parent_rule == ".gitignore:1:cache/\tcache/keep.txt\n", "excluded parent case mismatch")
        write(patterns, ".gitignore", "cache/*\n!cache/keep.txt\n")
        keep = git(patterns, "status", "--short", "--", "cache/keep.txt")
        other = git(patterns, "status", "--short", "--ignored", "--", "cache/discard.txt")
        require(keep == "?? cache/keep.txt\n" and other == "!! cache/discard.txt\n",
                "child-level exception case mismatch")
        cases.append({"case": "excluded_parent_negation", "excluded_parent_rule": parent_rule,
                      "after_child_pattern_keep_status": keep, "other_file_status": other})

        version = git(root, "--version").strip()
    return {"experiment_date": "2026-10-22",
            "environment": {"python": platform.python_version(), "platform": platform.platform(),
                            "git": version},
            "scope": "Local disposable repositories only; no network, real repository migration, secrets or history rewrite.",
            "cases_passed": cases, "command_trace": trace, "status": "passed"}


if __name__ == "__main__":
    print(json.dumps(run_lab(), ensure_ascii=False, indent=2))
