"""Render a Markdown patch report from analyzer outputs."""
from bot.lib.diff import Diff
from bot.lib.grep import CallSite


def _esc(s: str) -> str:
    return s.replace("|", "\\|")


def render(
    *,
    branch: str,
    new_version: str,
    new_build: int,
    previous_version: str,
    previous_build: int,
    detected_at: str,
    diff: Diff,
    sites: list[CallSite],
) -> str:
    lines: list[str] = []
    lines.append(f"# CritMatic patch report: WoW {new_version} (build {new_build})")
    lines.append("")
    lines.append(f"**Branch:** {branch}")
    lines.append(f"**Detected at:** {detected_at}")
    lines.append(
        f"**Compared against:** previous build {previous_build} ({previous_version})"
    )
    lines.append("")
    lines.append(f"## At-risk call sites ({len(sites)})")
    lines.append("")
    if sites:
        lines.append("| Symbol | File | Line | Snippet |")
        lines.append("|--------|------|------|---------|")
        for s in sorted(sites, key=lambda x: (x.path, x.line)):
            lines.append(
                f"| `{_esc(s.symbol)}` | `{_esc(s.path)}` | {s.line} | `{_esc(s.snippet)}` |"
            )
        lines.append("")
    if diff.renamed:
        lines.append("## Possibly renamed (heuristic, verify manually)")
        lines.append("")
        lines.append("| Old | Candidate new |")
        lines.append("|-----|----------------|")
        for old, new in sorted(diff.renamed):
            lines.append(f"| `{_esc(old)}` | `{_esc(new)}` |")
        lines.append("")
    lines.append("## Raw diff stats")
    lines.append("")
    lines.append(f"- Removed: {len(diff.removed)}")
    lines.append(f"- Added: {len(diff.added)}")
    lines.append(f"- Renamed (heuristic): {len(diff.renamed)}")
    lines.append("")
    return "\n".join(lines)
