"""Reproducible descriptive analysis for the GPT mathematics tutor RCT."""
from pathlib import Path
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

INPUT = Path("inputs/final_data-430055b4633e.csv")
ORDER = ["control", "vanilla", "augmented"]
LABELS = {"control": "Control", "vanilla": "GPT Base", "augmented": "GPT Tutor"}

df = pd.read_csv(INPUT)
required = {"Student ID", "Treatment arm", "GPTBase", "GPTTutor", "Part2Tot", "Part3Tot", "Honors"}
missing = required - set(df.columns)
if missing:
    raise ValueError(f"Missing required columns: {sorted(missing)}")

# Paper main sample: exclude honors-designated classrooms.
analysis_df = df.loc[df["Honors"].eq(0)].copy()
expected_flags = {"control": (0, 0), "vanilla": (1, 0), "augmented": (0, 1)}
observed_flags = analysis_df.groupby("Treatment arm")[["GPTBase", "GPTTutor"]].first().to_dict("index")
for arm, flags in expected_flags.items():
    if tuple(observed_flags.get(arm, {}).values()) != flags:
        raise ValueError(f"Unexpected GPT coding for {arm}: {observed_flags.get(arm)}")

summary = (analysis_df.groupby("Treatment arm", observed=True)
           .agg(n_students=("Student ID", "nunique"),
                n_student_sessions=("Student ID", "size"),
                mean_part2_practice=("Part2Tot", "mean"),
                mean_part3_independent_exam=("Part3Tot", "mean"))
           .reindex(ORDER).reset_index().rename(columns={"Treatment arm": "treatment_arm"}))
summary.insert(1, "group", summary["treatment_arm"].map(LABELS))
summary.to_csv("group_summary.csv", index=False, float_format="%.6f")

x = np.arange(len(summary))
width = 0.36
fig, ax = plt.subplots(figsize=(8.4, 5.2), dpi=180)
bars1 = ax.bar(x - width/2, summary["mean_part2_practice"], width,
               label="Part 2: assisted practice", color="#4472C4")
bars2 = ax.bar(x + width/2, summary["mean_part3_independent_exam"], width,
               label="Part 3: independent exam (AI removed)", color="#ED7D31")
ax.set_title("Mean scores by treatment group (main sample; unadjusted)")
ax.set_xlabel("Experimental group")
ax.set_ylabel("Mean normalized score (0-1)")
ax.set_xticks(x, summary["group"])
ax.set_ylim(0, 0.8)
ax.legend(frameon=False)
ax.grid(axis="y", alpha=0.25)
ax.bar_label(bars1, fmt="%.3f", padding=3, fontsize=9)
ax.bar_label(bars2, fmt="%.3f", padding=3, fontsize=9)
fig.tight_layout()
fig.savefig("learning_results.png", bbox_inches="tight")
plt.close(fig)
print(summary.to_string(index=False, float_format=lambda v: f"{v:.6f}"))
