"""Guards the lesson's claim that deleting a committed secret does not remove it from git history."""
import os
import subprocess

KEY = "EXAMPLE-demo-key-0000-not-a-real-key"


def git(repo, *args):
    env = {**os.environ, "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_SYSTEM": os.devnull}
    run = subprocess.run(["git", "-C", str(repo), "-c", "user.name=demo", "-c", "user.email=demo@example.invalid",
                          "-c", "commit.gpgsign=false", *args], capture_output=True, text=True, env=env)
    assert run.returncode == 0, run.stderr
    return run.stdout


def test_a_deleted_secret_is_still_in_history_and_gitignore_stops_the_first_commit(tmp_path):
    git(tmp_path, "init", "-q")
    (tmp_path / ".gitignore").write_text(".env\n")
    (tmp_path / ".env").write_text(f"AI_API_KEY={KEY}\n")
    git(tmp_path, "add", "--all")
    git(tmp_path, "commit", "-q", "-m", "first")
    assert ".env" not in git(tmp_path, "ls-files")  # the ignore rule kept it out
    git(tmp_path, "add", "--force", ".env")  # one --force, the mistake
    git(tmp_path, "commit", "-q", "-m", "oops")
    git(tmp_path, "rm", "-q", "--cached", ".env")
    (tmp_path / ".env").unlink()
    git(tmp_path, "commit", "-q", "-m", "remove the file")
    assert not (tmp_path / ".env").exists() and ".env" not in git(tmp_path, "ls-files")
    assert KEY in git(tmp_path, "log", "--all", "-p")  # gone from the folder, still in the history
