"""Run with Python 3 and matplotlib to check the recorded decisions and rebuild figures."""

import csv
import re
from collections import Counter
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import FancyBboxPatch


ROOT = Path(__file__).resolve().parent
FIGURES = ROOT / "figures"
INK, MUTED, TEAL, RUST, GRID = "#172e39", "#4e6270", "#076b71", "#a33e20", "#d9e3e4"
plt.rcParams.update({"font.family": "DejaVu Sans", "text.color": INK,
                     "axes.labelcolor": MUTED, "xtick.color": MUTED, "ytick.color": INK})


def save(fig, filename):
    fig.savefig(FIGURES / filename, dpi=170, facecolor="white", bbox_inches="tight", pad_inches=.27)
    plt.close(fig)


def clean_axes(ax):
    for spine in ax.spines.values():
        spine.set_visible(False)
    ax.tick_params(length=0, pad=8)
    ax.set_axisbelow(True)
    ax.grid(axis="x", color=GRID, linewidth=.8)


def language_chart(totals):
    fig, ax = plt.subplots(figsize=(8.6, 6.5))
    fig.subplots_adjust(left=.24, top=.82, bottom=.13, right=.95)
    fig.suptitle("How often did the agent say yes or no?", x=.035, y=.98,
                 ha="left", fontfamily="DejaVu Serif", fontsize=21)
    for index, (label, col, marker, color) in enumerate([
        ("Explicit refusals", 0, "o", RUST), ("Acceptances", 1, "s", TEAL)
    ]):
        values = [counts[col] for counts in totals.values()]
        ax.scatter(values, range(len(values)), marker=marker, color=color, s=85, label=label, zorder=2)
        for y, x in enumerate(values):
            ax.annotate(str(x), (x, y), xytext=(-10 if index == 0 else 10, 0),
                        textcoords="offset points", ha="right" if index == 0 else "left",
                        va="center", fontsize=10, color=color)
    ax.set_yticks(range(len(totals)), totals.keys(), fontsize=12)
    ax.set_ylim(len(totals)-.5, -.5)
    ax.set(xlim=(0, 10), xticks=range(0, 11, 2), xlabel="Number of replies  ·  20 scenarios per language")
    ax.legend(loc="lower left", bbox_to_anchor=(-.01, 1.025), ncol=2, frameon=False, fontsize=11)
    clean_axes(ax)
    save(fig, "intake-by-language.png")


def outcome_chart(outcomes):
    labels = {"conditional / defer": "Deferred", "accepted": "Accepted",
              "explicit refusal": "Explicit refusal", "clarification": "Asked for clarification",
              "other": "Other"}
    fig, ax = plt.subplots(figsize=(8.5, 3.6))
    fig.subplots_adjust(left=.27, right=.93, top=.83, bottom=.20)
    fig.suptitle("A deferral was the most common reply", x=.025, y=.99, ha="left",
                 fontfamily="DejaVu Serif", fontsize=20)
    bars = ax.barh(list(labels.values()), [outcomes[k] for k in labels],
                   color=[MUTED, TEAL, RUST, MUTED, MUTED], height=.58)
    ax.bar_label(bars, padding=5, fontsize=11)
    ax.invert_yaxis()
    ax.set(xlim=(0, 80), xticks=range(0, 81, 20), xlabel="Number of replies  ·  200 original intake decisions")
    clean_axes(ax)
    save(fig, "decisions.png")


def design_diagram():
    fig, ax = plt.subplots(figsize=(9, 2.8))
    ax.set(xlim=(0, 1), ylim=(0, 1))
    ax.axis("off")
    ax.text(.015, .95, "What changed between sessions?", size=21, family="DejaVu Serif", va="top")
    for i, (heading, body) in enumerate([
        ("20 scenarios", "Same task and\npermission facts"),
        ("10 versions", "Request language\nand wording varied"),
        ("200 sessions", "One fresh session,\none English reply"),
        ("2 reviewers", "Scored replies with\nlanguage hidden"),
    ]):
        x = .015 + i*.253
        ax.add_patch(FancyBboxPatch((x, .15), .206, .52, boxstyle="round,pad=.012",
                                    facecolor="#e3f2ef" if i==1 else "#eff3f5",
                                    edgecolor=TEAL if i==1 else GRID))
        ax.text(x+.009, .54, heading, size=12, weight="bold", va="center")
        ax.text(x+.009, .34, body, size=10.3, linespacing=1.45, va="center")
        if i < 3:
            ax.annotate("", xy=(x+.239,.407), xytext=(x+.217,.407),
                        arrowprops=dict(arrowstyle="->", color=MUTED, lw=1.4))
    save(fig, "study-design.png")


def main():
    with (ROOT / "evidence/decisions.csv").open(encoding="utf-8", newline="") as handle:
        rows = list(csv.DictReader(handle))
    languages = list(dict.fromkeys(r["request_language"] for r in rows))
    assert len(languages) == 10 and len(rows) == 200
    disagreements = 0
    for row in rows:
        agree = row["reviewer_a"] == row["reviewer_b"]
        disagreements += int(not agree)
        assert bool(row["adjudicated"]) != agree
        final = row["reviewer_a"] if agree else row["adjudicated"]
        assert final == row["original_decision"]
    assert disagreements == 2
    totals = {}
    for language in languages:
        group = [r for r in rows if r["request_language"] == language]
        assert sorted(int(r["scenario"]) for r in group) == list(range(1, 21))
        original = Counter(r["original_decision"] for r in group)
        offline = Counter(r["offline_intake_decision"] for r in group)
        totals[language] = (original["explicit refusal"], original["accepted"],
                            offline["decline"], offline["ready"])
    html = (ROOT / "evidence/language-intake-statistics.html").read_text(encoding="utf-8")
    reported = {lang: tuple(map(int, counts)) for lang, *counts in
                re.findall(r"<tr><td>([^<]+)</td>" + r"<td>(\d+)</td>"*4 + r"</tr>", html)}
    assert totals == reported, "The decision records and the statistical report disagree"
    english_refusals = {r["scenario"] for r in rows if r["request_language"] == "English"
                        and r["original_decision"] == "explicit refusal"}
    crossovers = sum(r["original_decision"] == "accepted" and r["scenario"] in english_refusals for r in rows)
    print("Acceptances at scenarios explicitly refused in English:", crossovers)
    assert crossovers == 0
    for level in ("1", "19", "20"):
        print("Scenario", level, Counter(r["original_decision"] for r in rows if r["scenario"] == level))
    FIGURES.mkdir(exist_ok=True)
    language_chart(totals)
    outcome_chart(Counter(r["original_decision"] for r in rows))
    design_diagram()


if __name__ == "__main__":
    main()
