"""Demonstrate ignored versus tracked files using dummy data in a temporary repo."""

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


def main():
    if not shutil.which("git"):
        raise SystemExit("Git is required.")
    with tempfile.TemporaryDirectory(prefix="git-env-demo-") as directory:
        root = Path(directory)
        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)

        def git(*args):
            return subprocess.run(
                ["git", "-c", "core.hooksPath=" + os.devnull,
                 "-c", "commit.gpgsign=false", *args],
                cwd=root, env=env, check=True, capture_output=True, text=True,
            ).stdout.strip()

        git("init", "--quiet")
        git("config", "user.name", "Local Demo")
        git("config", "user.email", "demo@example.invalid")
        dummy = "DEMO_TOKEN=NOT_A_REAL_SECRET\n"
        (root / ".env").write_text(dummy, encoding="utf-8")
        git("add", "--", ".env")
        git("commit", "--quiet", "-m", "Add dummy environment")
        first_commit = git("rev-parse", "HEAD")

        (root / ".gitignore").write_text("/.env\n", encoding="utf-8")
        git("add", "--", ".gitignore")
        git("commit", "--quiet", "-m", "Add ignore rule")
        assert git("ls-files", "--", ".env") == ".env"
        print("1. After .gitignore: tracked=.env")

        git("rm", "--cached", "--", ".env")
        assert (root / ".env").read_text(encoding="utf-8") == dummy
        assert git("ls-files", "--", ".env") == ""
        assert git("diff", "--cached", "--name-status") == "D\t.env"
        print("2. After rm --cached: local_exists=True, tracked=False")
        git("commit", "--quiet", "-m", "Stop tracking dummy environment")

        assert git("show", first_commit + ":.env") == dummy.strip()
        assert git("check-ignore", "--", ".env") == ".env"
        print("3. Earlier commit: dummy value still exists")

        (root / ".env.example").write_text("DEMO_TOKEN=\n", encoding="utf-8")
        git("add", "--", ".env.example")
        git("commit", "--quiet", "-m", "Add empty-value template")
        assert git("ls-files", "--", ".env.example") == ".env.example"
        assert git("status", "--porcelain") == ""
        print("4. Template tracked=.env.example; working tree clean")
    print("Temporary repository removed. No remote or real credentials used.")


if __name__ == "__main__":
    main()
