#!/usr/bin/env python3
"""leakscan: look for things in a release that point back to you.

Run it on every folder or repo before the persona publishes it.

  HIGH  a term from your private deny list (name, emails, hostnames, usernames,
        employer, collaborators...), or a credential
  MED   home-directory paths, email addresses, *.local hostnames, document and
        image metadata, notebook outputs, non-UTC commit timezones, extra
        git identities
  INFO  commit hour-of-day pattern, things worth a look

Exit status is 1 if anything HIGH or MED is found (0 with --allow-med for MED).
Your deny list should live outside every repo, e.g. ~/.config/pseudokit/deny.txt:
one term per line, case-insensitive substring; prefix with `re:` for a regex.
Standard library only; uses exiftool for image/PDF metadata if installed.
"""
from __future__ import annotations

import argparse
import json
import os
import re
import shutil
import subprocess
import sys
from collections import Counter
from pathlib import Path

DEFAULT_DENY = Path.home() / ".config" / "pseudokit" / "deny.txt"
MAX_BYTES = 50 * 1024 * 1024

SECRETS = [
    ("private key", r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----"),
    ("Anthropic key", r"sk-ant-[A-Za-z0-9_-]{20,}"),
    ("OpenAI key", r"\bsk-(?!ant-)(?:proj-)?[A-Za-z0-9_-]{32,}"),
    ("GitHub token", r"\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,})"),
    ("Hugging Face token", r"\bhf_[A-Za-z0-9]{30,}"),
    ("AWS key id", r"\bAKIA[0-9A-Z]{16}\b"),
    ("Slack token", r"\bxox[abposr]-[A-Za-z0-9-]{10,}"),
    ("W&B key", r"WANDB_API_KEY\s*=\s*\S{20,}"),
]
GENERIC = [
    ("home path", r"(?:/Users|/home)/(?!runner\b|user\b|ubuntu\b|<)[A-Za-z0-9._-]+|[A-Za-z]:\\\\?Users\\\\?[A-Za-z0-9._-]+"),
    ("email", r"\b[A-Za-z0-9._%+-]+@(?!example\.(?:com|org)|users\.noreply\.github\.com)[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"),
    (".local hostname", r"\b[A-Za-z0-9-]+\.local\b"),
]
RISKY_NAMES = {
    ".DS_Store": "Finder metadata (lists file names)", "__MACOSX": "macOS zip residue",
    ".env": "environment file", ".ipynb_checkpoints": "notebook autosaves",
    ".bash_history": "shell history", ".zsh_history": "shell history",
}
RISKY_SUFFIXES = {
    ".synctex.gz": "LaTeX synctex (absolute paths)", ".aux": "LaTeX aux", ".fls": "LaTeX file list (absolute paths)",
    ".log": "log file (paths, hostnames)", ".key": "key file",
    # .pem is not listed: public keys are meant to be published, and a private key
    # inside any file is already caught (HIGH) by its "PRIVATE KEY" header.
}
MEDIA = {".pdf", ".png", ".jpg", ".jpeg", ".tif", ".tiff", ".heic", ".gif", ".webp", ".svg",
         ".docx", ".pptx", ".xlsx", ".mp4", ".mov", ".m4a", ".wav"}


class Scan:
    def __init__(self, deny: list[tuple[str, re.Pattern]], allow_med: bool):
        self.deny, self.allow_med = deny, allow_med
        self.findings: list[tuple[str, str, str]] = []

    def add(self, level: str, where: str, what: str):
        self.findings.append((level, where, what))

    def text(self, where: str, text: str, generic: bool = True):
        for lineno, line in enumerate(text.splitlines(), 1):
            loc = f"{where}:{lineno}"
            for label, rx in self.deny:
                if rx.search(line):
                    self.add("HIGH", loc, f"deny-list term {label!r}: {snippet(line, rx)}")
            for label, pat in SECRETS:
                m = re.search(pat, line)
                if m:
                    self.add("HIGH", loc, f"{label}: {m.group(0)[:12]}...")
            if generic:
                for label, pat in GENERIC:
                    for m in re.finditer(pat, line):
                        self.add("MED", loc, f"{label}: {m.group(0)}")

    def report(self) -> int:
        order = {"HIGH": 0, "MED": 1, "INFO": 2}
        seen = set()
        for level, where, what in sorted(self.findings, key=lambda f: (order[f[0]], f[1])):
            if (level, where, what) in seen:
                continue
            seen.add((level, where, what))
            print(f"{level:4}  {where}  {what}")
        c = Counter(f[0] for f in self.findings)
        print(f"\n{c['HIGH']} high, {c['MED']} medium, {c['INFO']} info")
        if c["HIGH"] or (c["MED"] and not self.allow_med):
            return 1
        return 0


def snippet(line: str, rx: re.Pattern) -> str:
    m = rx.search(line)
    s = max(m.start() - 30, 0)
    return line[s:m.end() + 30].strip()


def load_deny(path: Path | None) -> list[tuple[str, re.Pattern]]:
    p = path or DEFAULT_DENY
    if not p.exists():
        if path:
            sys.exit(f"deny list {p} not found")
        print(f"note: no deny list at {p}; only generic checks will run", file=sys.stderr)
        return []
    out = []
    for raw in p.read_text().splitlines():
        t = raw.strip()
        if not t or t.startswith("#"):
            continue
        if t.startswith("re:"):
            out.append((t, re.compile(t[3:], re.I)))
        else:
            out.append((t, re.compile(re.escape(t), re.I)))
    return out


def walk(root: Path):
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = [d for d in dirnames if d != ".git"]
        for d in dirnames:
            yield Path(dirpath, d), True
        for f in filenames:
            yield Path(dirpath, f), False


def scan_names(s: Scan, rel: str, name: str):
    s.text(f"(file name) {rel}", rel, generic=False)
    if name in RISKY_NAMES:
        s.add("MED", rel, RISKY_NAMES[name])
    for suf, why in RISKY_SUFFIXES.items():
        if name.endswith(suf):
            s.add("MED", rel, why)


def scan_notebook(s: Scan, rel: str, data: bytes):
    try:
        nb = json.loads(data)
    except ValueError:
        return
    n = sum(1 for c in nb.get("cells", []) if c.get("outputs"))
    if n:
        s.add("MED", rel, f"notebook has outputs in {n} cells (paths, hostnames, usernames); clear them")
    meta = json.dumps(nb.get("metadata", {}))
    s.text(f"{rel} (metadata)", meta)


def png_text_chunks(data: bytes) -> list[str]:
    out, i = [], 8
    while i + 8 <= len(data):
        n = int.from_bytes(data[i:i + 4], "big")
        kind = data[i + 4:i + 8]
        if kind in (b"tEXt", b"iTXt", b"zTXt"):
            out.append(data[i + 8:i + 8 + n].replace(b"\0", b" ").decode("latin-1"))
        if kind == b"IEND":
            break
        i += 12 + n
    return out


def scan_media(s: Scan, rel: str, path: Path, data: bytes):
    ext = path.suffix.lower()
    meta_lines = []
    if shutil.which("exiftool"):
        r = subprocess.run(["exiftool", "-a", "-G1", "-s", str(path)], capture_output=True, text=True)
        skip = ("[System]", "[ExifTool]", "[File]")
        meta_lines = [l for l in r.stdout.splitlines() if not l.startswith(skip)]
    else:
        if ext == ".png":
            meta_lines = png_text_chunks(data)
        elif ext == ".pdf":
            meta_lines = [m.decode("latin-1") for m in re.findall(
                rb"/(?:Author|Creator|Producer|Title|Subject|Keywords)\s*\([^)]{0,300}\)", data)]
            meta_lines += [m.decode("latin-1") for m in re.findall(
                rb"<(?:dc:creator|xmp:CreatorTool|pdf:Producer)>.{0,300}?</", data, re.S)]
        elif ext in (".jpg", ".jpeg") and b"Exif\0\0" in data[:65536]:
            s.add("MED", rel, "JPEG has EXIF (camera, time, maybe GPS); strip it (install exiftool for details)")
    interesting = [l for l in meta_lines if re.search(
        r"author|creator|producer|artist|owner|user|host|path|software|gps|serial|comment|copyright|model|make",
        l, re.I)]
    if interesting:
        s.add("MED", rel, "metadata: " + " | ".join(l.strip()[:80] for l in interesting[:6]))
    s.text(f"{rel} (metadata)", "\n".join(meta_lines))


def scan_tree(s: Scan, root: Path):
    for path, is_dir in walk(root):
        rel = path.relative_to(root).as_posix()
        scan_names(s, rel, path.name)
        if is_dir or path.is_symlink():
            if path.is_symlink():
                s.text(f"{rel} (symlink target)", os.readlink(path))
            continue
        size = path.stat().st_size
        if size > MAX_BYTES:
            s.add("INFO", rel, f"skipped content scan ({size // 1_000_000} MB)")
            continue
        data = path.read_bytes()
        if path.suffix.lower() == ".ipynb":
            scan_notebook(s, rel, data)
        if path.suffix.lower() in MEDIA:
            scan_media(s, rel, path, data)
        if b"\0" in data[:8192]:
            # Binary: deny-list and secrets only, on printable runs.
            runs = "\n".join(m.decode("latin-1") for m in re.findall(rb"[\x20-\x7e]{6,}", data))
            s.text(f"{rel} (binary)", runs, generic=False)
        else:
            s.text(rel, data.decode("utf-8", errors="replace"))


def git(root: Path, *args: str) -> str:
    return subprocess.run(["git", "-C", str(root), *args], capture_output=True, text=True,
                          errors="replace").stdout


def scan_git(s: Scan, root: Path, persona_email: str | None):
    if not git(root, "rev-parse", "--git-dir").strip():
        return
    log = git(root, "log", "--all", "--format=%H%x09%an%x09%ae%x09%cn%x09%ce%x09%ad%x09%cd", "--date=iso-strict")
    idents, tzs, hours = Counter(), Counter(), Counter()
    for line in log.splitlines():
        h, an, ae, cn, ce, ad, cd = line.split("\t")
        idents[f"{an} <{ae}>"] += 1
        idents[f"{cn} <{ce}>"] += 1
        for d in (ad, cd):
            tzs["Z" if d.endswith("Z") else d[-6:]] += 1
        hours[int(ad[11:13])] += 1
        s.text(f"git {h[:10]} (author)", f"{an} <{ae}>\n{cn} <{ce}>", generic=False)
    if not idents:
        return
    if len(idents) > 1 or (persona_email and not any(persona_email in i for i in idents)):
        s.add("MED", "git history", "identities: " + ", ".join(f"{k} x{v}" for k, v in idents.most_common()))
    non_utc = {k: v for k, v in tzs.items() if k not in ("+00:00", "Z")}
    if non_utc:
        s.add("MED", "git history", f"non-UTC timezones in commit dates: {non_utc} (commit with TZ=UTC; "
              "rewriting history needs git filter-repo)")
    if sum(hours.values()) >= 10:
        busy = sorted(h for h, n in hours.items() if n)
        s.add("INFO", "git history", f"author hours used (as recorded): {busy}; a steady pattern hints at your "
              "timezone and job. Batch commits or squash before publishing.")
    # Commit messages and every past version of every file.
    patch = git(root, "log", "--all", "-p", "--no-color", "--format=commit %H%n%B")
    cur = "?"
    lines = []
    for line in patch.splitlines():
        if line.startswith("commit ") and len(line) == 47:
            cur = line[7:17]
            continue
        if line.startswith(("+", " ")) or not line.startswith(("-", "@@", "diff ", "index ", "---", "+++")):
            lines.append((cur, line))
    for c, line in lines:
        s.text(f"git {c} (history)", line)
    cfg = git(root, "config", "user.email").strip()
    if persona_email and cfg and cfg != persona_email:
        s.add("HIGH", "git config", f"user.email here is {cfg}, not the persona's {persona_email}")


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(prog="leakscan", description=__doc__.split("\n\n")[0],
                                 epilog="See the module docstring for levels and the deny-list format.")
    ap.add_argument("path", nargs="+", help="folders or repos to scan")
    ap.add_argument("--deny", type=Path, help=f"deny list (default {DEFAULT_DENY})")
    ap.add_argument("--persona-email", help="the only email that should appear in git history")
    ap.add_argument("--no-git", action="store_true", help="skip git history")
    ap.add_argument("--allow-med", action="store_true", help="exit 0 when only MED findings remain")
    a = ap.parse_args(argv)
    s = Scan(load_deny(a.deny), a.allow_med)
    for p in map(Path, a.path):
        scan_tree(s, p)
        if not a.no_git:
            scan_git(s, p, a.persona_email)
    return s.report()


if __name__ == "__main__":
    sys.exit(main())
