"""Markdown PR-comment body.

Layout: a TL;DR header (cluster table), then per-cluster sections grouping
findings, then a collapsible "Low-confidence (Discouraged)" section.
"""

from __future__ import annotations

from typing import Iterable

from ..classifier import ClassifiedFinding, ClusterSummary

CLUSTER_NAMES = {
    1: "Abuse of Functions",
    2: "Exploiting Server",
    3: "Exploiting Client",
    4: "Identity Theft",
    5: "Man in the Middle",
    6: "Flooding Attack",
    7: "Malware",
    8: "Physical Attack",
    9: "Social Engineering",
    10: "Supply Chain Attack",
}


def render(
    findings: Iterable[ClassifiedFinding],
    summary: dict[int, ClusterSummary],
    tlctc_version: str,
    sonar_project: str | None = None,
) -> str:
    findings_list = list(findings)
    lines: list[str] = []
    lines.append("## TLCTC SAST Report")
    if sonar_project:
        lines.append(f"_Project: `{sonar_project}` &middot; TLCTC v{tlctc_version}_")
    else:
        lines.append(f"_TLCTC v{tlctc_version}_")
    lines.append("")

    classified = [f for f in findings_list if f.resolved]
    low_conf = [f for f in findings_list if f.low_confidence and not f.resolved]

    lines.append(f"**Findings classified:** {len(classified)} &nbsp;|&nbsp; "
                 f"**Low-confidence:** {len(low_conf)} &nbsp;|&nbsp; "
                 f"**Total issues seen:** {len(findings_list)}")
    lines.append("")

    if summary:
        lines.append("### Cluster Exposure")
        lines.append("")
        lines.append("| Cluster | Name | Count |")
        lines.append("|---|---|---:|")
        for cs in summary.values():
            name = CLUSTER_NAMES.get(cs.cluster.number, "")
            lines.append(f"| `#{cs.cluster.number}` | {name} | {cs.count} |")
        lines.append("")

    for cs in summary.values():
        cluster_findings = [f for f in classified if any(c.number == cs.cluster.number for c in f.primary_clusters)]
        if not cluster_findings:
            continue
        name = CLUSTER_NAMES.get(cs.cluster.number, "")
        lines.append(f"### `#{cs.cluster.number}` {name} &mdash; {len(cluster_findings)} finding(s)")
        lines.append("")
        for f in cluster_findings:
            lines.append(f"- **{f.issue_key}** &mdash; `{f.component}`")
            lines.append(f"  - Rule: `{f.rule}` (severity `{f.severity}`, type `{f.type}`)")
            lines.append(f"  - CWE: {', '.join(f.cwe_refs) if f.cwe_refs else '_none_'}")
            for r in f.resolved:
                lines.append(
                    f"  - {r.entry.cwe_id} &rarr; `{str(r.resolution.resolved)}` "
                    f"({r.entry.verdict}) &mdash; {r.resolution.reason}"
                )
            if f.message:
                lines.append(f"  - _{f.message}_")
        lines.append("")

    if low_conf:
        lines.append("<details>")
        lines.append("<summary>Low-confidence findings (Discouraged verdict)</summary>")
        lines.append("")
        for f in low_conf:
            cwes = ", ".join(f.cwe_refs) if f.cwe_refs else "_none_"
            lines.append(f"- **{f.issue_key}** &mdash; `{f.component}` ({cwes})")
            for r in f.low_confidence:
                lines.append(
                    f"  - {r.entry.cwe_id} ({r.entry.verdict}) &mdash; "
                    f"raw mapping `{r.entry.tlctc_mapping}`"
                )
        lines.append("</details>")
        lines.append("")

    lines.append("---")
    lines.append(f"_Generated by `tlctc-sonar` against the canonical CWE&rarr;TLCTC mapping._")

    return "\n".join(lines).rstrip() + "\n"
