"""Markdown report for diff results - designed for PR comments."""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from cloud_audit.diff import DiffResult, FindingChange


def _escape_md(value: str) -> str:
    """Escape markdown-breaking characters in table cell values."""
    return value.replace("|", "\\|").replace("\n", " ")


def _findings_table(findings: list[FindingChange]) -> list[str]:
    """Render a list of FindingChange as a markdown table."""
    if not findings:
        return []
    lines: list[str] = []
    lines.append("| Severity | Check | Resource | Title |")
    lines.append("|----------|-------|----------|-------|")
    for f in findings:
        sev = f"**{f.severity.value.upper()}**"
        check_id = _escape_md(f.check_id)
        resource = _escape_md(f.resource_id)
        resource = resource[:40] + "..." if len(resource) > 40 else resource
        title = _escape_md(f.title)
        title = title[:60] + "..." if len(title) > 60 else title
        lines.append(f"| {sev} | {check_id} | `{resource}` | {title} |")
    return lines


def generate_diff_markdown(diff: DiffResult) -> str:
    """Generate a Markdown diff report string."""
    lines: list[str] = []

    # Header
    lines.append("## cloud-audit diff")
    lines.append("")

    # Score change
    sign = "+" if diff.score_change >= 0 else ""
    lines.append(f"**Score:** {diff.old_score} -> {diff.new_score} ({sign}{diff.score_change})")
    lines.append(f"**Findings:** {diff.old_total} -> {diff.new_total}")
    lines.append("")

    # Scope warnings
    if diff.scope_warnings:
        for w in diff.scope_warnings:
            lines.append(f"> **Warning:** {w}")
        lines.append("")

    # New findings (regressions)
    if diff.new_findings:
        lines.append(f"### New findings ({len(diff.new_findings)})")
        lines.append("")
        lines.extend(_findings_table(diff.new_findings))
        lines.append("")
    else:
        lines.append("### No new findings")
        lines.append("")

    # Fixed findings
    if diff.fixed_findings:
        lines.append(f"### Fixed ({len(diff.fixed_findings)})")
        lines.append("")
        lines.extend(_findings_table(diff.fixed_findings))
        lines.append("")

    # Changed severity
    if diff.changed_findings:
        lines.append(f"### Changed severity ({len(diff.changed_findings)})")
        lines.append("")
        lines.append("| Check | Resource | Old | New |")
        lines.append("|-------|----------|-----|-----|")
        for f in diff.changed_findings:
            old_sev = f.old_severity.value.upper() if f.old_severity else "?"
            new_sev = f.severity.value.upper()
            resource = _escape_md(f.resource_id)
            resource = resource[:40] + "..." if len(resource) > 40 else resource
            lines.append(f"| {f.check_id} | `{resource}` | {old_sev} | {new_sev} |")
        lines.append("")

    # Unchanged
    if diff.unchanged_findings:
        lines.append(f"<details><summary>Unchanged ({len(diff.unchanged_findings)})</summary>")
        lines.append("")
        lines.extend(_findings_table(diff.unchanged_findings))
        lines.append("")
        lines.append("</details>")
        lines.append("")

    # Footer
    lines.append("---")
    lines.append("*Generated by [cloud-audit](https://github.com/gebalamariusz/cloud-audit)*")
    lines.append("")

    return "\n".join(lines)
