"""Render a compact E04 baseline-versus-replay comparison from saved summaries."""
import argparse
import csv
import hashlib
import json
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt


def read_summary(path):
    with path.open(encoding="utf-8", newline="") as stream:
        return next(row for row in csv.DictReader(stream) if row["condition"] == "combined")


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def render(baseline, replay, output):
    baseline_row = read_summary(baseline)
    replay_row = read_summary(replay)
    plt.rcParams.update({
        "font.sans-serif": ["Microsoft YaHei", "DejaVu Sans"],
        "font.size": 9,
        "axes.spines.top": False,
        "axes.spines.right": False,
        "axes.unicode_minus": False,
    })

    labels = ["60° 基准", "30° 复跑"]
    rows = [baseline_row, replay_row]
    x = [0, 1]
    blue = "#245d85"
    gray = "#707070"
    fig, axes = plt.subplots(1, 2, figsize=(8, 3.2), layout="constrained")

    for ax, median_key, p95_key, ylabel in (
        (axes[0], "translation_error_mm_median", "translation_error_mm_p95", "安装平移误差 / mm"),
        (axes[1], "rotation_error_deg_median", "rotation_error_deg_p95", "安装旋转误差 / °"),
    ):
        medians = [float(row[median_key]) for row in rows]
        p95 = [float(row[p95_key]) for row in rows]
        ax.plot(x, medians, color=blue, marker="o", linewidth=1.4, markersize=5, label="中位数")
        ax.scatter(x, p95, color=gray, marker="s", facecolors="none", linewidths=1.2, label="P95")
        for xi, value, high in zip(x, medians, p95):
            ax.vlines(xi, value, high, color=gray, linewidth=1)
        ax.set_xticks(x, labels)
        ax.set_ylabel(ylabel)
        ax.grid(axis="y", color=".9", linewidth=.6)
        ax.set_axisbelow(True)
        ax.margins(x=.25, y=.18)

    axes[0].legend(frameon=False, loc="upper left")
    fig.suptitle("E04 组合噪声下的角度幅度对比", fontsize=10)
    output.parent.mkdir(parents=True, exist_ok=True)
    fig.savefig(output, dpi=190, facecolor="white")
    plt.close(fig)

    manifest = {
        "baseline_summary_sha256": digest(baseline),
        "replay_summary_sha256": digest(replay),
        "renderer_sha256": digest(Path(__file__)),
        "figure_sha256": digest(output),
        "figure": output.name,
        "condition": "combined",
        "rounds_per_condition": 30,
    }
    output.with_suffix(".manifest.json").write_text(
        json.dumps(manifest, indent=2) + "\n", encoding="utf-8"
    )
    print(json.dumps(manifest, indent=2))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--baseline", type=Path, required=True)
    parser.add_argument("--replay", type=Path, required=True)
    parser.add_argument("--out", type=Path, required=True)
    args = parser.parse_args()
    render(args.baseline, args.replay, args.out)
