"""Plot the saved Week 5 assignment and queue teaching constructions.

Run the lab first, then from the course root:
  conda run -n research python assets/scripts/build-week5-management.py

Inputs are generated lab CSVs, copied byte-for-byte to assets/data. All data
and parameters are synthetic. No article figure or empirical interval is used.
"""
from pathlib import Path
import csv
import math
import os
import sys

BOOK = Path(__file__).resolve().parents[2]
REPO = BOOK.parents[1]
os.environ.setdefault("MPLCONFIGDIR", str(BOOK / ".mpl-cache"))
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

sys.path.insert(0, str(REPO))
from shared.figure_style import COLORS, apply_style, save_figure, style_axis

MODE = "SYNTHETIC_TEACHING_CONSTRUCTION_NOT_PUBLISHED_REPLICATION"
LAB = BOOK / "labs/05-managers-hierarchies-authority-and-delegation"


def read_generated(name, input_name):
    source = LAB / "output/reproduced" / name
    with source.open(newline="") as stream:
        rows = list(csv.DictReader(stream))
    assert rows and all(row["mode"] == MODE for row in rows)
    target = BOOK / "assets/data" / input_name
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_bytes(source.read_bytes())
    return rows


def save(fig, name):
    path = BOOK / "assets/figures" / name
    save_figure(fig, path.with_suffix(".png"))
    fig.savefig(path.with_suffix(".pdf"), bbox_inches="tight", facecolor="white",
                metadata={"CreationDate": None, "ModDate": None})
    plt.close(fig)


def main():
    event = read_generated("event_time_contrasts.csv", "05-manager-event-time.csv")
    queue = read_generated("queue_illustration.csv", "05-manager-queue.csv")
    assert len(event) == 9 and [int(r["event_time"]) for r in event] == list(range(-3, 6))
    assert all(r["reference"] == "mean_of_three_pre_periods_not_tminus1" for r in event)
    assert abs(sum(float(r["paired_contrast"]) for r in event[:3])) < 1e-8
    assert all(math.isfinite(float(r["paired_contrast"])) for r in event)
    assert all(float(r["se_across_pairs"]) > 0 for r in event)
    assert len(queue) == 4
    for r in queue:
        arrival = int(r["span"]) * float(r["problem_rate_per_worker"]) * float(r["escalation_share"])
        capacity = float(r["service_rate"])
        assert math.isclose(arrival, float(r["arrival_rate"]), abs_tol=1e-8)
        assert bool(int(r["stationary"])) == (arrival < capacity)
        if arrival < capacity:
            assert math.isclose(float(r["mean_sojourn_minutes"]), 60 / (capacity-arrival), abs_tol=1e-8)
        else:
            assert r["mean_sojourn_minutes"] == ""
    assert [r["span"] for r in queue] == ["10", "30", "40", "30"]
    apply_style()
    fig, ax = plt.subplots(figsize=(10.5, 5.6))
    x = [int(r["event_time"]) for r in event]
    y = [float(r["paired_contrast"]) for r in event]
    ax.axvspan(-3.4, -0.5, color=COLORS["navy"], alpha=0.06)
    ax.axhline(0, color=COLORS["muted"], linewidth=1)
    ax.axvline(0, color=COLORS["rust"], linewidth=1.2, linestyle="--")
    ax.plot(x, y, color=COLORS["navy"], marker="o", linewidth=2, markersize=6)
    ax.text(0.15, 3.35, "Every team receives a replacement manager", fontsize=10, color=COLORS["rust"])
    ax.text(-1.9, 3.05, "Pre-periods", ha="center", color=COLORS["muted"], fontsize=10)
    ax.set(title="Randomized incoming-manager contrast", xlabel="Event period (arrival = 0)",
           ylabel="High minus low: output change\nfrom each team's mean pre-period output",
           xticks=x, xlim=(-3.4, 5.35), ylim=(-0.55, 3.75))
    style_axis(ax)
    fig.text(0.5, 0.112, "24 invented teams · 12 matched pairs · fixed roster · equal pair weights", ha="center", fontsize=10, color=COLORS["muted"])
    fig.text(0.5, 0.068, "Reference: mean of three pre-periods, not period −1. Points only; no empirical confidence bands.", ha="center", fontsize=9, color=COLORS["muted"])
    fig.text(0.5, 0.022, MODE, ha="center", fontsize=8, color=COLORS["muted"])
    fig.tight_layout(rect=(0, 0.16, 1, 1))
    save(fig, "05-manager-assignment-event-time")

    fig, ax = plt.subplots(figsize=(10.5, 5.6))
    positions = [0, 1, 3]
    values = [float(queue[i]["mean_sojourn_minutes"]) for i in positions]
    bars = ax.bar(positions, values, width=.57, color=[COLORS["navy"], COLORS["rust"], COLORS["teal"]])
    ax.bar_label(bars, labels=["20 min", "60 min", "24 min"], padding=5, fontsize=11)
    ax.axvspan(1.6, 2.4, facecolor=COLORS["muted"], alpha=.07, hatch="//", edgecolor=COLORS["muted"])
    ax.text(2, 40, "No stationary\ndistribution\nλ = μ = 4", ha="center", va="center", color=COLORS["muted"], fontsize=11)
    ax.set(title="Attention congestion depends on span and escalation", ylabel="Mean time: waiting + service (minutes)",
           xticks=[0, 1, 2, 3], xticklabels=["10 workers\n20% escalate", "30 workers\n20% escalate", "40 workers\n20% escalate", "30 workers\n10% escalate"],
           ylim=(0, 75), xlim=(-.55, 3.55))
    ax.tick_params(axis="x", labelsize=10)
    style_axis(ax)
    fig.text(.5, .112, "M/M/1 teaching model: 0.5 problems per worker-hour; manager capacity 4 per hour.", ha="center", fontsize=9, color=COLORS["muted"])
    fig.text(.5, .068, "Poisson arrivals · exponential service · one server · no abandonment · invented parameters", ha="center", fontsize=9, color=COLORS["muted"])
    fig.text(.5, .022, MODE, ha="center", fontsize=8, color=COLORS["muted"])
    fig.tight_layout(rect=(0, .16, 1, 1))
    save(fig, "05-manager-attention-queue")
    print("PASS: 9 event periods and 4 queue scenarios verified; exact CSV inputs and two PNG/PDF figures saved.")


if __name__ == "__main__":
    main()
