"""Small I/O and execution checks shared by the accuracy examples."""
from pathlib import Path
import argparse
import importlib.util
import json
import sys
import numpy as np

DATA = Path(__file__).resolve().parents[1]/"data"
BACKENDS = ("optix", "vulkan", "embree")
COLORS = ("#2563a6", "#d47713", "#27976b")
MARKERS = ("o", "s", "^")


def reference(name):
    path = Path(__file__).with_name(name+"_reference.py")
    if not path.exists():
        path = Path(__file__).resolve().parents[4]/"tests/reference"/(name+".py")
    spec = importlib.util.spec_from_file_location(name+"_reference", path)
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    return module


def inputs(name):
    return json.loads((DATA/name/"input.json").read_text(encoding="utf-8"))


def execution(product, backend, workflow, program):
    identity = product.metadata["execution"]
    expected = dict(backend=backend, workflow=workflow, executor=f"{backend}.slang.{program}", native=True)
    assert all(identity[key] == value for key, value in expected.items()), identity
    return expected


def write_result(output, result):
    output.mkdir(parents=True, exist_ok=True)
    (output/"results.json").write_text(json.dumps(result, indent=2, allow_nan=False)+"\n", encoding="utf-8")


def arguments(name):
    parser = argparse.ArgumentParser(description=name+" accuracy validation")
    parser.add_argument("--backend", choices=BACKENDS)
    parser.add_argument("--output", type=Path, default=Path("build")/name)
    parser.add_argument("--figures-only", action="store_true")
    return parser.parse_args()


def plot_settings():
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    plt.rcParams.update({"svg.fonttype": "none", "font.size": 10,
        "axes.spines.top": False, "axes.spines.right": False})
    return plt


def convergence(panel, studies, xlabel="Samples", ylabel="RMSE"):
    for backend, color, marker in zip(BACKENDS, COLORS, MARKERS):
        selected = [s for s in studies if s["backend"] == backend]
        if not selected:
            continue
        budgets = [x["samples"] for x in selected[0]["levels"]]
        errors = [float(np.sqrt(np.mean([s["levels"][i]["rmse"]**2 for s in selected])))
                  for i in range(len(budgets))]
        panel.loglog(budgets, np.maximum(errors, 1e-12), color=color, marker=marker,
                     markerfacecolor="none", label=backend)
    panel.set(xlabel=xlabel, ylabel=ylabel)
    panel.grid(alpha=.15)
    panel.legend(frameon=False, fontsize=8)
