"""Hash archive files and list references to absent executable/data assets.

Usage: python3 src/audit_inventory.py --archive-root PATH --output-dir results
The reference list is a literal-reference inventory, not proof the asset never existed.
"""
import argparse
import csv
import hashlib
import re
from pathlib import Path
from collections import Counter


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--archive-root", type=Path, required=True)
    p.add_argument("--output-dir", type=Path, required=True)
    args = p.parse_args()
    root = args.archive_root.resolve()
    args.output_dir.mkdir(parents=True, exist_ok=True)
    files = sorted(f for f in root.rglob("*") if f.is_file())
    names = {f.name for f in files}
    rows = []
    refs = set()
    counts = Counter()
    for f in files:
        relative = str(f.relative_to(root))
        data = f.read_bytes()
        branch = f.relative_to(root).parts[1] if relative.startswith("bsd_source/") and len(f.relative_to(root).parts)>2 else "root"
        counts[(branch, f.suffix)] += 1
        rows.append([relative, len(data), hashlib.sha256(data).hexdigest(), branch,
                     "Twin" if branch == "phase2" else "Lead", "read"])
        if f.suffix in {".md", ".html", ".txt"}:
            text = data.decode("utf-8")
            for name in re.findall(r"[A-Za-z0-9_][A-Za-z0-9_.-]*\.(?:py|sage|json|csv|tsv|jsonl|ipynb|zip|yaml)", text):
                if name not in names:
                    refs.add((relative, name))
    for filename, header, values in (
        ("archive_inventory.csv", ["path","bytes","sha256","branch","review_context","coverage"], rows),
        ("missing_asset_references.csv", ["referencing_file","absent_filename"], sorted(refs)),
    ):
        with (args.output_dir/filename).open("w", encoding="utf-8", newline="") as handle:
            writer = csv.writer(handle)
            writer.writerow(header)
            writer.writerows(values)
    print("inventory_files =", len(files))
    for key, value in sorted(counts.items()):
        print(key, value)
    print("literal_missing_asset_references =", len(refs))


if __name__ == "__main__":
    main()
