"""Summary-row contract and rendering to CSV + markdown."""
from __future__ import annotations

import csv
import io
from typing import Any, Dict, List

SUMMARY_FIELDS = [
    "method",
    "status",
    "t4_deployable",
    "model_size_mb",
    "mean_latency_s",
    "p50_latency_s",
    "p95_latency_s",
    "throughput_rps",
    "decode_tok_s",
    "mean_cer",
    "max_cer",
    "mean_bbox_iou",
    "mean_missed_lines",
    "mean_extra_lines",
    "error",
]


def build_row(**kwargs: Any) -> Dict[str, Any]:
    unknown = set(kwargs) - set(SUMMARY_FIELDS)
    if unknown:
        raise KeyError(f"unknown summary field(s): {sorted(unknown)}")
    row = {field: None for field in SUMMARY_FIELDS}
    row.update(kwargs)
    return row


def rows_to_csv(rows: List[Dict[str, Any]]) -> str:
    buf = io.StringIO()
    writer = csv.DictWriter(buf, fieldnames=SUMMARY_FIELDS)
    writer.writeheader()
    for row in rows:
        writer.writerow(row)
    return buf.getvalue()


def _fmt(value: Any) -> str:
    if value is None:
        return ""
    if isinstance(value, float):
        return f"{value:.4f}"
    return str(value)


def rows_to_markdown(rows: List[Dict[str, Any]]) -> str:
    header = "| " + " | ".join(SUMMARY_FIELDS) + " |"
    sep = "| " + " | ".join("---" for _ in SUMMARY_FIELDS) + " |"
    lines = [header, sep]
    for row in rows:
        lines.append("| " + " | ".join(_fmt(row[f]) for f in SUMMARY_FIELDS) + " |")
    return "\n".join(lines)
