"""Aggregate UNCLEAR + INTERNAL_RETHROW sites from the audit JSON output."""
import json
import sys
from collections import defaultdict
from pathlib import Path


def main() -> int:
    audit_path = Path("C:/Users/Ed/AppData/Local/Temp/audit_initial.json")
    if not audit_path.exists():
        print(f"Missing: {audit_path}", file=sys.stderr)
        return 1
    with audit_path.open("r", encoding="utf-8") as f:
        data = json.load(f)

    target_categories = {"UNCLEAR", "INTERNAL_RETHROW"}
    by_file: dict[str, list[dict]] = defaultdict(list)
    total = 0
    for file_info in data.get("files", []):
        for finding in file_info.get("findings", []):
            if finding.get("category") in target_categories:
                record = {
                    "line": finding.get("line"),
                    "kind": finding.get("kind"),
                    "context": finding.get("context"),
                    "category": finding.get("category"),
                }
                by_file[file_info["filename"]].append(record)
                total += 1

    print(f"Total sites in {sorted(target_categories)}: {total}")
    print(f"Files affected: {len(by_file)}")
    print()
    for filename in sorted(by_file):
        sites = by_file[filename]
        print(f"{filename}: {len(sites)} sites")
        for s in sites:
            print(f"  L{s['line']:>5}  {s['category']:<18}  {s['kind']:<7}  in {s['context']}")
        print()

    out_path = Path("scripts/tier2/artifacts/result_migration_review_pass_20260617/sites_to_classify.json")
    out_path.parent.mkdir(parents=True, exist_ok=True)
    with out_path.open("w", encoding="utf-8") as f:
        json.dump(
            {"total": total, "files": dict(by_file)},
            f,
            indent=2,
        )
    print(f"Wrote {out_path}")
    return 0


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