"""Markdown exporter — renders a Report as a readable Markdown document."""

from __future__ import annotations

from trustandverify.core.models import Report, Verdict

_VERDICT_EMOJI = {
    Verdict.SUPPORTED: "✅",
    Verdict.CONTESTED: "⚠️",
    Verdict.REFUTED: "❌",
    Verdict.NO_EVIDENCE: "❓",
}


class MarkdownExporter:
    """Render a Report to Markdown format."""

    format_name = "markdown"
    file_extension = ".md"

    def render(self, report: Report) -> str:
        lines: list[str] = []

        # Header
        lines += [
            "# TrustGraph Verification Report",
            "",
            f"**Query:** {report.query}",
            f"**Generated:** {report.created_at.strftime('%Y-%m-%d %H:%M UTC')}",
            f"**Claims verified:** {len(report.claims)}",
            "",
        ]

        # Summary
        if report.summary:
            lines += [
                "## Executive Summary",
                "",
                report.summary,
                "",
            ]

        # Claims
        lines += ["## Claims Analysis", ""]
        for i, claim in enumerate(report.claims, 1):
            emoji = _VERDICT_EMOJI.get(claim.verdict, "❓")
            verdict_str = claim.verdict.value.upper()

            op = claim.opinion
            if op:
                p = op.projected_probability()
                bdu = f"b={op.belief:.3f} / d={op.disbelief:.3f} / u={op.uncertainty:.3f}"
                p_str = f"{p:.3f}"
            else:
                p_str = "—"
                bdu = "—"

            lines += [
                f"### {i}. {emoji} {claim.text}",
                "",
                f"| Field | Value |",
                f"|---|---|",
                f"| Verdict | **{verdict_str}** |",
                f"| Projected probability | {p_str} |",
                f"| Subjective opinion | {bdu} |",
                "",
            ]

            if claim.assessment:
                lines += [f"**Assessment:** {claim.assessment}", ""]

            # Sources
            if claim.evidence:
                lines += ["**Sources:**", ""]
                for ev in claim.evidence:
                    icon = "✅" if ev.supports_claim else "❌"
                    label = "supports" if ev.supports_claim else "contradicts"
                    lines.append(
                        f"- {icon} [{ev.source.title}]({ev.source.url}) "
                        f"(trust: {ev.source.trust_score:.2f}, {label})"
                    )
                lines.append("")

        # Conflicts
        if report.conflicts:
            lines += ["## Evidence Conflicts", ""]
            for c in report.conflicts:
                lines += [
                    f"- **{c.claim_text}** — conflict degree: {c.conflict_degree:.3f} "
                    f"({c.num_supporting} supporting vs {c.num_contradicting} contradicting)",
                ]
            lines.append("")

        # Footer
        lines += [
            "---",
            "",
            "*Generated by [trustandverify](https://github.com/jemsbhai/trustandverify) "
            "using Subjective Logic confidence algebra (Jøsang 2016).*",
        ]

        return "\n".join(lines)

    def render_to_file(self, report: Report, path: str) -> None:
        with open(path, "w", encoding="utf-8") as fh:
            fh.write(self.render(report))
