from __future__ import annotations

import json
from dataclasses import asdict
from typing import Dict

from .types import Report


def report_to_dict(report: Report) -> Dict[str, object]:
    return asdict(report)


def write_report_json(report: Report, path: str) -> None:
    with open(path, "w", encoding="utf-8") as handle:
        json.dump(report_to_dict(report), handle, indent=2, sort_keys=True)


def render_markdown(report: Report) -> str:
    summary = report.summary
    lines = ["# CiteSleuth Report", "", "## Summary", ""]
    lines.append("| Verdict | Count |")
    lines.append("| --- | ---: |")
    for verdict, count in summary.get("counts", {}).items():
        lines.append(f"| {verdict} | {count} |")

    issues = summary.get("issues", {})
    if issues:
        lines.append("")
        lines.append("## Top Issues")
        for label, items in issues.items():
            lines.append("")
            lines.append(f"### {label}")
            for item in items:
                lines.append(f"- {item}")

    lines.append("")
    lines.append("## Entries")
    for result in report.results:
        lines.append("")
        lines.append(f"### {result.ref_id}")
        lines.append(f"- Verdict: {result.verdict}")
        lines.append(f"- Score: {result.score:.2f}")
        if result.reasons:
            lines.append(f"- Reasons: {'; '.join(result.reasons)}")
        if result.patch:
            lines.append("- Suggested Patch:")
            for key, value in result.patch.items():
                lines.append(f"  - {key}: {value}")
    return "\n".join(lines)


def write_report_markdown(report: Report, path: str) -> None:
    with open(path, "w", encoding="utf-8") as handle:
        handle.write(render_markdown(report))
