"""Additional output formatters."""

from __future__ import annotations

from collections import defaultdict

from .models import SEVERITY_ORDER, CheckResult

PROJECT_LINK = "https://github.com/mordecai/agentlint"


def _summary_rows(findings: list[CheckResult]) -> list[tuple[str, str, int]]:
    counts: dict[tuple[str, str], int] = defaultdict(int)
    for finding in findings:
        counts[(finding.check_id, finding.severity)] += 1
    rows = [(check_id, severity, count) for (check_id, severity), count in counts.items()]
    rows.sort(key=lambda row: (SEVERITY_ORDER[row[1]], row[0]))
    return rows


def _findings_by_file(findings: list[CheckResult]) -> dict[str, list[CheckResult]]:
    grouped: dict[str, list[CheckResult]] = defaultdict(list)
    for finding in findings:
        grouped[finding.file_path or "<unknown>"].append(finding)

    for file_findings in grouped.values():
        file_findings.sort(
            key=lambda item: (
                SEVERITY_ORDER[item.severity],
                item.line or -1,
                item.check_id,
                item.message,
            )
        )
    return dict(sorted(grouped.items(), key=lambda item: item[0]))


def _line_suffix(line: int | None) -> str:
    if line is None:
        return ""
    return f":{line}"


def render_markdown(findings: list[CheckResult]) -> str:
    rows = _summary_rows(findings)
    grouped = _findings_by_file(findings)

    lines: list[str] = [
        "# agentlint Report",
        "",
        "## Summary",
        "",
        "| Check | Severity | Count |",
        "| --- | --- | --- |",
    ]
    if rows:
        for check_id, severity, count in rows:
            lines.append(f"| `{check_id}` | `{severity}` | {count} |")
    else:
        lines.append("| `-` | `-` | 0 |")

    lines.extend(["", "## Findings by File", ""])
    if not grouped:
        lines.append("No findings.")
    else:
        for file_path, file_findings in grouped.items():
            lines.append(f"<details><summary><code>{file_path}</code> ({len(file_findings)} findings)</summary>")
            lines.append("")
            for finding in file_findings:
                lines.append(
                    f"- `{finding.severity}` `{finding.check_id}` `{file_path}{_line_suffix(finding.line)}`: {finding.message}"
                )
            lines.append("")
            lines.append("</details>")
            lines.append("")

    lines.extend(
        [
            "---",
            f"Generated by [agentlint]({PROJECT_LINK}).",
        ]
    )
    return "\n".join(lines).rstrip()
