"""Phase 12.5: Triage the post-fix audit findings.

For each file with violations/UNCLEAR, list the sites with file:line + category + note.
Group by file. Save to docs/reports/PHASE12_TRIAGE_20260617.md.
"""
from __future__ import annotations
import json
from pathlib import Path
from collections import defaultdict

with open(r"docs/reports/PHASE12_AUDIT_POST_FIX_20260617.json") as f:
    d = json.load(f)

# Group by file
by_file = defaultdict(list)
for f_info in d["files"]:
    fname = f_info["filename"]
    for finding in f_info["findings"]:
        if finding["category"] in ("INTERNAL_SILENT_SWALLOW", "INTERNAL_BROAD_CATCH",
                                     "INTERNAL_OPTIONAL_RETURN", "UNCLEAR", "INTERNAL_RETHROW"):
            by_file[fname].append(finding)

# Phase 12 plan files (priority order)
priority_files = [
    "src/api_hooks.py",
    "src/warmup.py",
    "src/startup_profiler.py",
    "src/file_cache.py",
    "src/orchestrator_pm.py",
    "src/project_manager.py",
    "src/log_registry.py",
    "src/models.py",
    "src/multi_agent_conductor.py",
    "src/theme_2.py",
    "src/shell_runner.py",
    "src/session_logger.py",
]

# Output
out = []
out.append("# Phase 12.5 — Triage of Post-Fix Audit Findings\n")
out.append("**Date:** 2026-06-17 (auto-generated)\n")
out.append("**Source:** `docs/reports/PHASE12_AUDIT_POST_FIX_20260617.json`\n")
out.append("**Total sites:** " + str(d.get("total_sites", "?")) + "\n")
out.append("**Violation sites:** " + str(d.get("violation_sites", "?")) + "\n")
out.append("**UNCLEAR sites:** " + str(d.get("unclear_sites", "?")) + "\n\n")
out.append("This triage enumerates the migration-target sites per file, ")
out.append("in priority order (Phase 12 plan 12.6 sub-batches).\n\n")

for fname in priority_files:
    sites = by_file.get(fname, [])
    if not sites:
        out.append(f"## `{fname}` — NO violations (clean)\n\n")
        continue
    out.append(f"## `{fname}` — {len(sites)} sites to migrate\n\n")
    out.append("| Line | Category | Note |\n")
    out.append("|---|---|---|\n")
    for s in sorted(sites, key=lambda x: x["line"]):
        note = s.get("note", s.get("hint", "")).replace("|", "\\|").replace("\n", " ")[:120]
        out.append(f"| {s['line']} | {s['category']} | {note} |\n")
    out.append("\n")

# Catch-all: other files with violations
out.append("\n## Other files with violations (not in priority list)\n\n")
for fname in sorted(by_file.keys()):
    if fname in priority_files:
        continue
    sites = by_file[fname]
    out.append(f"### `{fname}` — {len(sites)} sites\n\n")
    out.append("| Line | Category | Note |\n")
    out.append("|---|---|---|\n")
    for s in sorted(sites, key=lambda x: x["line"]):
        note = s.get("note", s.get("hint", "")).replace("|", "\\|").replace("\n", " ")[:120]
        out.append(f"| {s['line']} | {s['category']} | {note} |\n")
    out.append("\n")

# Total counts
out.append("\n## Summary by category\n\n")
out.append("| Category | Count |\n|---|---|\n")
from collections import Counter
cats = Counter()
for f_info in d["files"]:
    for finding in f_info["findings"]:
        cats[finding["category"]] += 1
for c, n in cats.most_common():
    out.append(f"| {c} | {n} |\n")

p = Path("docs/reports/PHASE12_TRIAGE_20260617.md")
p.write_text("".join(out), encoding="utf-8", newline="\n")
print(f"wrote {p}: {len(''.join(out))} chars")
print(f"\nPriority file summary:")
for fname in priority_files:
    sites = by_file.get(fname, [])
    print(f"  {fname}: {len(sites)} sites")