"""Record the demo’s learning curves and test sensitivity to seeds and password pairs.

Run beside train.py:
uv run --python 3.13 --with torch==2.15.0 --with numpy --with matplotlib==3.10.8 python experiments.py
"""

import json
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import torch
from torch.nn import functional as F

from train import (
    ATTENTION_FEEDBACK_WEIGHT,
    HELD_OUT_PAIRS,
    PASSWORDS,
    TRAIN_STEPS,
    batch,
    build_models,
    examples,
    fit,
    measure,
)

HERE = Path(__file__).resolve().parent
SEEDS = (0, 1, 2, 3, 4)
VALIDATION_INTERVAL = 20
VALIDATION_PAIRS = (HELD_OUT_PAIRS[0],)
SPLIT_LABELS = ("Same password", "Demo split", "Other rotation")
MODEL_STYLES = {
    "linear": ("Single layer", "#a7b2a3", "--"),
    "mlp": ("MLP", "#d3b8f2", ":"),
    "transformer": ("Transformer", "#b6f66b", "-"),
}
BACKGROUND = "#121410"
PANEL = "#191c16"
INK = "#e8ece5"
MUTED = "#b8c2b4"
GRID = "#3a4436"
ACCENT = "#b6f66b"
BLUE = "#9fd7ee"


def demo_curves():
    torch.manual_seed(0)
    train = batch(examples(held_out=False))
    validation = batch(examples(held_out=True, pairs=VALIDATION_PAIRS))
    tokens, targets, _ = train
    results = {}

    for name, model in build_models().items():
        training_loss = []
        validation_accuracy = []

        def observe(current_model, update):
            with torch.no_grad():
                loss = F.cross_entropy(current_model(tokens), targets)
            training_loss.append(round(loss.item(), 7))
            if update % VALIDATION_INTERVAL == 0 or update == TRAIN_STEPS:
                correct = measure(current_model, validation)["password"]
                validation_accuracy.append({"update": update, "correct": correct})

        attention_weight = ATTENTION_FEEDBACK_WEIGHT if name == "transformer" else 0.0
        fit(model, train, attention_weight=attention_weight, observe=observe)
        results[name] = {
            "trainingCrossEntropy": training_loss,
            "validationPasswords": validation_accuracy,
        }

    return results


def split_sensitivity():
    runs = []
    for offset, label in enumerate(SPLIT_LABELS):
        pairs = tuple(
            (fox, PASSWORDS[(index + offset) % len(PASSWORDS)])
            for index, fox in enumerate(PASSWORDS)
        )
        train = batch(examples(held_out=False, pairs=pairs))
        test = batch(examples(held_out=True, pairs=pairs))
        for seed in SEEDS:
            for guided in (False, True):
                torch.manual_seed(seed)
                # Initialize in the same order as the published demo. The two
                # conditions start with identical weights for a given seed.
                model = build_models()["transformer"]
                weight = ATTENTION_FEEDBACK_WEIGHT if guided else 0.0
                fit(model, train, attention_weight=weight)
                result = measure(model, test)
                runs.append({
                    "split": label,
                    "heldOutPairs": pairs,
                    "seed": seed,
                    "clueFeedback": guided,
                    "correct": result["password"],
                    "total": result["total"],
                })
    return runs


def style_chart():
    plt.rcParams.update({
        "figure.facecolor": BACKGROUND,
        "axes.facecolor": PANEL,
        "axes.edgecolor": GRID,
        "axes.labelcolor": MUTED,
        "axes.titlecolor": INK,
        "xtick.color": MUTED,
        "ytick.color": MUTED,
        "text.color": INK,
        "grid.color": GRID,
        "font.family": "DejaVu Sans",
        "font.size": 14,
        "svg.fonttype": "path",
        "svg.hashsalt": "password-riddle-experiments",
    })


def save_plot(figure, filename):
    figure.savefig(HERE / filename, metadata={"Date": None})
    plt.close(figure)


def plot_curves(curves):
    fig, (loss, validation) = plt.subplots(2, 1, figsize=(5.65, 6.15), sharex=True)
    for name, (label, color, linestyle) in MODEL_STYLES.items():
        curve = curves[name]
        loss.plot(curve["trainingCrossEntropy"], label=label, color=color, linestyle=linestyle, linewidth=2)
        samples = curve["validationPasswords"]
        validation.step(
            [point["update"] for point in samples], [point["correct"] for point in samples],
            where="post", color=color, linestyle=linestyle, linewidth=2,
        )

    loss.set_title("Training loss", loc="left", pad=8)
    loss.set_ylabel("Cross-entropy")
    loss.set_ylim(bottom=0)
    loss.set_yticks([0, 0.5, 1.0, 1.5])
    validation.set_title("Validation passwords correct", loc="left", pad=8)
    validation.set_ylabel("Out of 4")
    validation.set_yticks(range(5))
    validation.set_ylim(-0.2, 4.2)
    validation.set_xlabel("Weight updates")
    validation.set_xlim(0, TRAIN_STEPS)
    validation.set_xticks([0, 200, 400, 600])
    for axis in (loss, validation):
        axis.grid(axis="y", alpha=0.8)
        axis.set_axisbelow(True)
    handles, labels = loss.get_legend_handles_labels()
    fig.legend(handles, labels, loc="upper center", ncol=3, frameon=False, fontsize=13,
               bbox_to_anchor=(0.54, 0.995), columnspacing=1.05)
    fig.subplots_adjust(left=0.19, right=0.96, top=0.86, bottom=0.11, hspace=0.38)
    save_plot(fig, "training-curves.svg")


def plot_sensitivity(runs):
    fig, axis = plt.subplots(figsize=(5.65, 3.75))
    center = (len(SEEDS) - 1) / 2
    for guided, color, marker, label in (
        (True, ACCENT, "o", "Feedback on"),
        (False, BLUE, "D", "Feedback off"),
    ):
        points = [run for run in runs if run["clueFeedback"] is guided]
        axis.scatter(
            [run["correct"] for run in points],
            [SPLIT_LABELS.index(run["split"]) + (0.2 if guided else -0.2)
             + (SEEDS.index(run["seed"]) - center) * 0.082 for run in points],
            c=color, marker=marker, s=23, label=label, clip_on=False,
        )
    for boundary in (0.5, 1.5):
        axis.axhline(boundary, color=GRID, linewidth=0.8)
    axis.set(yticks=range(len(SPLIT_LABELS)), yticklabels=SPLIT_LABELS, ylim=(2.5, -0.5))
    axis.set(xticks=[0, 3, 6, 9, 12], xlim=(-0.35, 12.35), xlabel="Held-out passwords correct (out of 12)")
    axis.tick_params(axis="y", length=0, labelsize=12)
    axis.grid(axis="x", alpha=0.8)
    axis.set_axisbelow(True)
    handles, labels = axis.get_legend_handles_labels()
    fig.legend(handles, labels, loc="upper center", ncol=2, frameon=False,
               bbox_to_anchor=(0.59, 0.995), columnspacing=1.2, fontsize=13)
    fig.subplots_adjust(left=0.32, right=0.94, top=0.84, bottom=0.21)
    save_plot(fig, "split-results.svg")


def main():
    torch.set_num_threads(1)
    curves = demo_curves()
    runs = split_sensitivity()
    results = {
        "updates": TRAIN_STEPS,
        "demoSeed": 0,
        "validationPairs": VALIDATION_PAIRS,
        "attentionFeedbackWeight": ATTENTION_FEEDBACK_WEIGHT,
        "curves": curves,
        "splitRuns": runs,
    }
    (HERE / "experiment-results.json").write_text(json.dumps(results, separators=(",", ":")) + "\n", encoding="utf-8")
    style_chart()
    plot_curves(curves)
    plot_sensitivity(runs)
    for guided in (True, False):
        scores = [run["correct"] for run in runs if run["clueFeedback"] is guided]
        print(f"Clue feedback {guided}: {min(scores)}–{max(scores)} of 12", flush=True)


if __name__ == "__main__":
    main()
