"""C1: illustrate target-note error versus the current nearest-note calculation.

Run from a checkout: python3 scripts/make_self_recording_reference_examples.py
Requires matplotlib and rustc. Frequencies are assigned, not measured audio.
"""
import csv
import hashlib
import io
import json
import math
from pathlib import Path
import shutil
import subprocess
import tempfile

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

ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "blog/assets/singing_recorder/research-review"


def main():
    OUT.mkdir(parents=True, exist_ok=True)
    source = (ROOT / "src/tools/pitch_plot.rs").read_text()
    start = source.index("fn cents_from_freq_f64(")
    opening = source.index("{", start)
    end, depth = opening + 1, 1
    while depth:
        depth += (source[end] == "{") - (source[end] == "}")
        end += 1
    function = source[start:end]
    runner = function + r'''
fn main() {
    let input = std::fs::read_to_string(std::env::args().nth(1).unwrap()).unwrap();
    println!("case_id,target_hz,produced_hz,target_error_cents,nearest_note_error_cents");
    for line in input.lines().skip(1) {
        let cols: Vec<&str> = line.split(',').collect();
        let target: f64 = cols[1].parse().unwrap();
        let produced: f64 = cols[2].parse().unwrap();
        println!("{},{:.9},{:.9},{:.9},{:.9}", cols[0], target, produced,
            1200.0 * (produced / target).log2(), cents_from_freq_f64(produced).unwrap());
    }
}
'''
    (OUT / "reference-reproduction.rs").write_text(runner)
    with (OUT / "frequency-inputs.csv").open("w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["case_id", "target_hz", "produced_hz"])
        for name, cents in [("correct_A4", 0), ("wrong_B4", 200), ("flat_A4", -30)]:
            writer.writerow([name, 440.0, format(440 * 2 ** (cents / 1200), ".12f")])
    with tempfile.TemporaryDirectory() as temp:
        binary = Path(temp) / "reference-example"
        subprocess.run(["rustc", "--edition=2021", "-O", str(OUT / "reference-reproduction.rs"), "-o", str(binary)], check=True)
        result = subprocess.check_output([str(binary), str(OUT / "frequency-inputs.csv")], text=True)
    rows = list(csv.DictReader(io.StringIO(result)))
    for row in rows:
        produced = float(row["produced_hz"])
        target = 1200 * math.log2(produced / float(row["target_hz"]))
        midi = 69 + 12 * math.log2(produced / 440)
        nearest = 100 * (midi - math.floor(midi + 0.5))
        assert math.isclose(float(row["target_error_cents"]), target, abs_tol=1e-7)
        assert math.isclose(float(row["nearest_note_error_cents"]), nearest, abs_tol=1e-7)
    (OUT / "reference-results.csv").write_text(result)
    (OUT / "reference-results.json").write_text(json.dumps({
        "role": "Assigned-frequency calculation illustration; not a singer, audio analysis, browser test, or paper dataset.",
        "source": "src/tools/pitch_plot.rs::cents_from_freq_f64",
        "function_sha256": hashlib.sha256(function.encode()).hexdigest(),
        "rustc": subprocess.check_output(["rustc", "--version"], text=True).strip(),
        "verification": "Extracted unchanged Rust function agrees with independent Python formulas within 1e-7 cents; no rounding-boundary cases.",
        "results": rows,
    }, indent=2) + "\n")
    fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharey=True)
    for ax, key, title in zip(axes,
            ["target_error_cents", "nearest_note_error_cents"],
            ["Error relative to target A4", "Error relative to nearest note"]):
        ax.bar(["A4 correct", "B4 wrong note", "A4 flat"], [float(r[key]) for r in rows], color=["#667eea", "#a8b4ff", "#6b7280"])
        ax.axhline(0, color="#242a42", linewidth=0.8)
        ax.set_title(title, fontsize=11)
        ax.set_ylim(-55, 230)
        ax.spines[["top", "right"]].set_visible(False)
        for i, row in enumerate(rows):
            value = float(row[key])
            ax.text(i, value + (8 if value >= 0 else -15), f"{value:+.0f} cents", ha="center", fontsize=10)
    axes[0].set_ylabel("Signed error (cents)")
    fig.tight_layout()
    fig.savefig(OUT / "target-vs-nearest-note.png", dpi=180, facecolor="white")
    plt.close(fig)
    shutil.copyfile(__file__, OUT / Path(__file__).name)
    print(f"Verified {len(rows)} assigned-frequency examples; assets written to {OUT}")


if __name__ == "__main__":
    main()
