#!/usr/bin/env python3
"""contextpacker.py — Zero-dependency repo-to-LLM prompt packer with secret redaction.

Usage:
    python3 contextpacker.py . -o context.xml
    python3 contextpacker.py ./src --format markdown -o prompt.md

Part of ContextPacker by Node24Lab (24h Autonomous AI Experiment).
Support / Ko-fi: https://ko-fi.com/node24lab
"""

from __future__ import annotations

import argparse
import re
from pathlib import Path

SKIP_DIRS = {
    ".git", "node_modules", "dist", "build", ".next", "__pycache__",
    ".venv", "venv", "target", "vendor", ".cache", "coverage",
}
BINARY_EXTS = {
    ".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico", ".pdf", ".zip",
    ".tar", ".gz", ".woff", ".woff2", ".ttf", ".mp3", ".mp4", ".pyc", ".wasm",
}
SECRET_RULES = [
    re.compile(r"\b(?:sk-(?:proj-|ant-|live-|test-)?[A-Za-z0-9_-]{20,}|rk_live_[A-Za-z0-9]{16,}|pk_live_[A-Za-z0-9]{16,})\b"),
    re.compile(r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b"),
    re.compile(r"\bgithub_pat_[A-Za-z0-9_]{30,}\b"),
    re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
    re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{12,}\b"),
    re.compile(r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----"),
    re.compile(r"\bBearer\s+[A-Za-z0-9._-]{20,}\b", re.IGNORECASE),
]
ENV_SECRET_RE = re.compile(
    r"^([A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|ACCESS_KEY)[A-Z0-9_]*\s*[:=]\s*)([\"']?)[^\s\"'\r\n]{6,}\2",
    re.MULTILINE,
)


def redact_text(text: str) -> tuple[str, int]:
    total = 0
    for rule in SECRET_RULES:
        text, n = rule.subn("[REDACTED_SECRET]", text)
        total += n
    text, n_env = ENV_SECRET_RE.subn(r"\1\2[REDACTED_SECRET]\2", text)
    total += n_env
    return text, total


def collect_files(root: Path, max_bytes: int) -> list[tuple[str, str, int]]:
    items: list[tuple[str, str, int]] = []
    for p in sorted(root.rglob("*")):
        if not p.is_file():
            continue
        rel_parts = p.relative_to(root).parts
        if any(part in SKIP_DIRS for part in rel_parts[:-1]):
            continue
        if p.suffix.lower() in BINARY_EXTS or p.name in {"package-lock.json", "yarn.lock", "pnpm-lock.yaml"}:
            continue
        if p.stat().st_size > max_bytes:
            continue
        try:
            raw = p.read_text(encoding="utf-8")
        except Exception:
            continue
        cleaned, count = redact_text(raw)
        items.append((p.relative_to(root).as_posix(), cleaned, count))
    return items


def main() -> int:
    ap = argparse.ArgumentParser(description="Pack a local repository into an LLM prompt with automatic secret redaction.")
    ap.add_argument("path", default=".", nargs="?", help="Directory to pack")
    ap.add_argument("-o", "--out", default="context.xml", help="Output file path")
    ap.add_argument("--format", choices=("xml", "markdown"), default="xml", help="Output format")
    ap.add_argument("--max-bytes", type=int, default=262144, help="Skip files larger than N bytes")
    args = ap.parse_args()

    root = Path(args.path).resolve()
    items = collect_files(root, args.max_bytes)
    total_redacted = sum(c for _, _, c in items)

    lines: list[str] = []
    if args.format == "xml":
        lines.append("<repository_context>")
        lines.append("<file_tree>")
        for rel, _, c in items:
            lines.append(f"- {rel}" + (f" ({c} secret(s) redacted)" if c else ""))
        lines.append("</file_tree>")
        lines.append("<files>")
        for rel, content, _ in items:
            lines.append(f'<file path="{rel}">')
            lines.append(content.replace("</file>", "</_file>"))
            lines.append("</file>")
        lines.append("</files>")
        lines.append("</repository_context>")
    else:
        lines.append("# Repository Context\n")
        for rel, content, _ in items:
            ext = rel.rsplit(".", 1)[-1] if "." in rel else ""
            lines.append(f"## `{rel}`\n\n```{ext}\n{content}\n```\n")

    output = "\n".join(lines)
    Path(args.out).write_text(output, encoding="utf-8")
    print(f"Packed {len(items)} files (~{len(output)//4} tokens, {total_redacted} secret(s) redacted) -> {args.out}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
