#!/usr/bin/env python3
"""Lab: what is really inside a repository directory?

Builds a small synthetic repository in a temporary directory, plants four
canary strings in places a developer would call "gone", and then measures
which ways of exporting the project still carry them.

Time is part of the experiment. Git measures reflog expiry from the date of each
reflog entry and the prune grace period from file times. In this script every
reflog entry takes its date from GIT_COMMITTER_DATE, so the script sets both:

* the main run dates everything today ("the developer did this just now");
* a second run dates everything 45 days ago and ages the object files to match,
  then lets the same default ``git gc`` decide what is left.

Nothing here touches a real repository, a network, or a real secret.
Usage:  python3 run.py [--age-days N] [--keep] [--out results.json]
"""
from __future__ import annotations

import argparse
import fnmatch
import io
import json
import os
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
from datetime import date, timedelta
from pathlib import Path

CANARIES = {
    "A": ("SBX-CANARY-A-7f3a91c2d4", "committed, then deleted and added to .gitignore"),
    "B": ("SBX-CANARY-B-0be4c77a19", "ignored working file, never committed"),
    "C": ("SBX-CANARY-C-5d20aa8e63", "committed on a branch that was deleted"),
    "D": ("SBX-CANARY-D-c41e09b7f5", "stashed, then the stash was dropped"),
}
DENY_PATHS = ["*.env", "*.sql", "*.pem", "*.key", "id_rsa*"]  # a typical path filter
AGED_DAYS = 45  # past Git's reflog expiry (30 days) and prune grace period (2 weeks)

ENV = dict(
    os.environ,
    GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM="1",
    GIT_AUTHOR_NAME="lab", GIT_AUTHOR_EMAIL="lab@example.invalid",
    GIT_COMMITTER_NAME="lab", GIT_COMMITTER_EMAIL="lab@example.invalid",
    LC_ALL="C",
)


def set_clock(age_days: int) -> str:
    """Date every commit and reflog entry ``age_days`` before today, at 00:00 local time.

    A date fixed in this file would change the result by itself once it was
    30 days old, because reflog expiry is measured from it.
    """
    day = date.today() - timedelta(days=age_days)
    stamp = f"{day.isoformat()}T00:00:00"
    ENV["GIT_AUTHOR_DATE"] = ENV["GIT_COMMITTER_DATE"] = stamp
    return stamp


def age_objects(repo: Path, age_days: int) -> None:
    """Give the object files a modification time ``age_days`` ago.

    The prune grace period (gc.pruneExpire, two weeks) is measured from file
    times, not from commit dates.
    """
    when = time.time() - age_days * 86400
    for p in (repo / ".git" / "objects").rglob("*"):
        if p.is_file():
            os.utime(p, (when, when))


def git(repo: Path, *args: str, check: bool = True) -> str:
    done = subprocess.run(["git", "-C", str(repo), *args], env=ENV, capture_output=True, text=True)
    if check and done.returncode:
        raise SystemExit(f"git {' '.join(args)} failed: {done.stderr.strip()}")
    return done.stdout


def write(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8")


def build_repo(repo: Path, age_days: int = 0) -> str:
    stamp = set_clock(age_days)
    repo.mkdir(parents=True)
    git(repo, "init", "-q", "-b", "main")
    write(repo / "README.md", "# billing-service\n\nSynthetic project for a lab.\n")
    write(repo / "src/app.py", "def total(items):\n    return sum(i.price for i in items)\n")
    write(repo / "docs/design.md", "# Design\n\n" + "Lorem ipsum dolor sit amet. " * 200 + "\n")
    write(repo / "config/settings.env", f"API_TOKEN={CANARIES['A'][0]}\nREGION=ap-northeast-1\n")
    git(repo, "add", "-A")
    git(repo, "commit", "-q", "-m", "initial import")

    # "We removed the secret and ignored the file."
    git(repo, "rm", "-q", "config/settings.env")
    write(repo / ".gitignore", "*.env\n!*.example.env\n")
    write(repo / "config/settings.example.env", "API_TOKEN=\nREGION=\n")
    git(repo, "add", "-A")
    git(repo, "commit", "-q", "-m", "remove settings.env, ignore env files")

    # An ignored local file: present on disk, unknown to Git.
    write(repo / "config/local.env", f"API_TOKEN={CANARIES['B'][0]}\n")

    # A spike branch that is deleted before anyone pushes it.
    git(repo, "switch", "-q", "-c", "spike/customer-export")
    write(repo / "schema/customers.sql", f"-- export key {CANARIES['C'][0]}\nCREATE TABLE customers (id INT, email TEXT);\n")
    git(repo, "add", "-A")
    git(repo, "commit", "-q", "-m", "spike: customer export")
    git(repo, "switch", "-q", "main")
    git(repo, "branch", "-q", "-D", "spike/customer-export")

    # A stash that is dropped.
    write(repo / "src/app.py", f"DEBUG_TOKEN = '{CANARIES['D'][0]}'\n\ndef total(items):\n    return sum(i.price for i in items)\n")
    git(repo, "stash", "push", "-q", "-m", "debug token")
    git(repo, "stash", "drop", "-q")

    # Routine maintenance with default settings (no --prune=now).
    if age_days:
        age_objects(repo, age_days)
    git(repo, "gc", "-q")
    return stamp


def tree_stats(root: Path) -> tuple[int, int]:
    files = [p for p in root.rglob("*") if p.is_file()]
    return len(files), sum(p.stat().st_size for p in files)


def scan_objects(repo: Path) -> set[str]:
    """Canaries recoverable from every object Git can still enumerate."""
    found: set[str] = set()
    listing = git(repo, "cat-file", "--batch-all-objects", "--batch-check", check=False)
    for line in listing.splitlines():
        sha, kind, _size = line.split()
        if kind != "blob":
            continue
        data = subprocess.run(["git", "-C", str(repo), "cat-file", "blob", sha], env=ENV, capture_output=True).stdout
        for name, (token, _why) in CANARIES.items():
            if token.encode() in data:
                found.add(name)
    return found


def scan_files(root: Path, skip_git: bool = True) -> set[str]:
    """Canaries visible as plain bytes in files (what a string scanner sees)."""
    found: set[str] = set()
    for p in root.rglob("*"):
        if not p.is_file() or (skip_git and ".git" in p.relative_to(root).parts):
            continue
        data = p.read_bytes()
        for name, (token, _why) in CANARIES.items():
            if token.encode() in data:
                found.add(name)
    return found


def raw_hits(root: Path) -> set[str]:
    return scan_files(root, skip_git=False)


def measure(label: str, how: str, root: Path, has_git: bool) -> dict:
    files, size = tree_stats(root)
    plain = scan_files(root)
    in_objects = scan_objects(root) if has_git else set()
    return {
        "export": label,
        "how": how,
        "files": files,
        "bytes": size,
        "canaries_in_plain_files": sorted(plain),
        "canaries_in_git_objects": sorted(in_objects),
        "canaries_recoverable": sorted(plain | in_objects),
        "canaries_seen_by_byte_scan": sorted(raw_hits(root)),
    }


def repo_stats(repo: Path) -> dict:
    return {
        "commits_reachable_from_refs": int(git(repo, "rev-list", "--count", "--all").strip() or 0),
        "objects_total": len(git(repo, "cat-file", "--batch-all-objects", "--batch-check").splitlines()),
        "unreachable_ignoring_reflog": len(git(repo, "fsck", "--unreachable", "--no-reflogs", check=False).splitlines()),
        "unreachable_with_reflog": len(git(repo, "fsck", "--unreachable", check=False).splitlines()),
        "count_objects": dict(
            line.split(": ") for line in git(repo, "count-objects", "-v").strip().splitlines()
        ),
    }


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--age-days", type=int, default=0, help="date the main run this many days ago (default 0)")
    ap.add_argument("--keep", action="store_true", help="keep the temporary directory")
    ap.add_argument("--out", default=str(Path(__file__).with_name("results.json")))
    args = ap.parse_args()

    work = Path(tempfile.mkdtemp(prefix="sbx-git-lab-"))
    repo = work / "billing-service"
    stamp = build_repo(repo, args.age_days)
    results = []

    # (a) Copy of the working tree without .git
    a = work / "a-worktree"
    shutil.copytree(repo, a, ignore=shutil.ignore_patterns(".git"))
    results.append(measure("worktree-copy", "copy files, skip .git", a, False))

    # (b) git archive HEAD
    b = work / "b-archive"
    b.mkdir()
    blob = subprocess.run(["git", "-C", str(repo), "archive", "HEAD"], env=ENV, capture_output=True).stdout
    tarfile.open(fileobj=io.BytesIO(blob)).extractall(b, filter="data")
    results.append(measure("git-archive", "git archive HEAD", b, False))

    # (c) Everything reachable from refs
    c = work / "c-clone"
    git(repo, "bundle", "create", "-q", str(work / "all.bundle"), "--all")
    subprocess.run(["git", "clone", "-q", str(work / "all.bundle"), str(c)], env=ENV, check=True, capture_output=True)
    # Note: the clone stores the absolute path of the bundle in its config and reflog,
    # so the byte count of this export changes with the temporary directory.
    results.append(measure("ref-clone", "git bundle --all, then clone", c, True))

    # (d) The whole directory, .git included
    d = work / "d-directory"
    shutil.copytree(repo, d, symlinks=True)
    results.append(measure("directory-snapshot", "copy the whole directory", d, True))

    # (e) The whole directory, after a path-based deny list
    e = work / "e-filtered"
    dropped = []

    def deny(directory: str, names: list[str]) -> list[str]:
        out = [n for n in names if any(fnmatch.fnmatch(n, pat) for pat in DENY_PATHS)]
        dropped.extend(str(Path(directory, n).relative_to(repo)) for n in out)
        return out

    shutil.copytree(repo, e, symlinks=True, ignore=deny)
    row = measure("path-filtered-snapshot", "copy the directory, drop paths matching a deny list", e, True)
    row["deny_patterns"] = DENY_PATHS
    row["paths_dropped_by_filter"] = sorted(dropped)
    results.append(row)

    git_paths = [str(p.relative_to(repo)) for p in (repo / ".git").rglob("*") if p.is_file()]
    report = {
        "lab": "git-boundary",
        "git_version": git(repo, "--version").strip(),
        "python": sys.version.split()[0],
        "canaries": {k: v[1] for k, v in CANARIES.items()},
        "run_date": date.today().isoformat(),
        "commit_age_days": args.age_days,
        "commit_date": stamp,
        "repository": {
            **repo_stats(repo),
            "git_dir_files": len(git_paths),
            "git_dir_paths_matching_deny_list": [
                p for p in git_paths if any(fnmatch.fnmatch(Path(p).name, pat) for pat in DENY_PATHS)
            ],
            "head_tree": git(repo, "ls-tree", "-r", "--name-only", "HEAD").split(),
        },
        "exports": results,
    }

    # The same repository, 45 days later: commit dates and object file times are both
    # 45 days old when the same default gc runs. Only the whole directory is measured.
    old = work / "aged" / "billing-service"
    old_stamp = build_repo(old, AGED_DAYS)
    aged = measure("directory-snapshot", "the whole directory, in place", old, True)
    report["aged"] = {
        "commit_age_days": AGED_DAYS,
        "commit_date": old_stamp,
        "repository": repo_stats(old),
        "canaries_recoverable": aged["canaries_recoverable"],
        "canaries_seen_by_byte_scan": aged["canaries_seen_by_byte_scan"],
    }
    Path(args.out).write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")

    print(f"{report['git_version']}  |  objects: {report['repository']['objects_total']}"
          f"  |  .git files: {len(git_paths)}  |  .git paths matching deny list: "
          f"{len(report['repository']['git_dir_paths_matching_deny_list'])}")
    print(f"{'export':<24}{'files':>6}{'bytes':>9}  {'recoverable':<12}{'byte-scan sees':<15}")
    for r in results:
        print(f"{r['export']:<24}{r['files']:>6}{r['bytes']:>9}  "
              f"{''.join(r['canaries_recoverable']) or '-':<12}{''.join(r['canaries_seen_by_byte_scan']) or '-':<15}")
    print(f"{'same, ' + str(AGED_DAYS) + ' days old':<24}{'':>6}{'':>9}  "
          f"{''.join(report['aged']['canaries_recoverable']) or '-':<12}"
          f"{''.join(report['aged']['canaries_seen_by_byte_scan']) or '-':<15}")
    if args.keep:
        print("kept:", work)
    else:
        shutil.rmtree(work, ignore_errors=True)


if __name__ == "__main__":
    main()
