"""Markdown report renderer for eval results."""

from __future__ import annotations

from llmhq_releaseops.models.eval_result import EvalReport


class MarkdownReporter:
    """Generates a human-readable Markdown report from an EvalReport."""

    @staticmethod
    def render(report: EvalReport) -> str:
        lines: list[str] = []

        # Header
        lines.append(f"# Eval Report: {report.suite_id}")
        lines.append("")
        lines.append(f"- **Bundle**: {report.bundle_id} v{report.bundle_version}")
        lines.append(f"- **Timestamp**: {report.timestamp}")
        if report.bundle_hash:
            lines.append(f"- **Bundle Hash**: `{report.bundle_hash[:16]}...`")
        lines.append("")

        # Summary
        s = report.summary
        lines.append("## Summary")
        lines.append("")
        lines.append("| Metric | Value |")
        lines.append("|--------|-------|")
        lines.append(f"| Total Cases | {s.total_cases} |")
        lines.append(f"| Passed | {s.passed} |")
        lines.append(f"| Failed | {s.failed} |")
        lines.append(f"| Pass Rate | {s.pass_rate:.0%} |")
        lines.append(f"| Gate Decision | **{s.gate_decision.value}** |")
        lines.append("")

        if not report.results:
            lines.append("_No test cases were executed._")
            return "\n".join(lines)

        # Per-case results
        lines.append("## Results")
        lines.append("")

        for result in report.results:
            status = "PASS" if result.passed else "FAIL"
            lines.append(f"### {result.case_id}: {status}")
            lines.append("")

            if result.error:
                lines.append(f"**Error**: {result.error}")
                lines.append("")
                continue

            if result.latency_ms is not None:
                lines.append(f"- Latency: {result.latency_ms:.0f}ms")

            if result.output:
                truncated = result.output[:200]
                if len(result.output) > 200:
                    truncated += "..."
                lines.append(f"- Output: `{truncated}`")

            lines.append("")

            for ar in result.assertions:
                status_icon = "PASS" if ar.passed else "FAIL"
                lines.append(
                    f"  - [{status_icon}] {ar.judge_type} "
                    f"(confidence={ar.confidence:.2f}, weight={ar.weight})"
                )
                if ar.reasoning:
                    lines.append(f"    - {ar.reasoning}")

            lines.append("")

        # Failed cases summary
        failed = report.failed_cases
        if failed:
            lines.append("## Failed Cases")
            lines.append("")
            for fc in failed:
                reason = fc.error or "assertions failed"
                lines.append(f"- **{fc.case_id}**: {reason}")
            lines.append("")

        return "\n".join(lines)
