"""Synthetic sensor QA teaching model. Standard library only. Run to reproduce all outputs.
No measured sensor data; numerical thresholds illustrate coverage gaps, not certification.
"""

import csv
import json
import math
import statistics
from itertools import pairwise
from pathlib import Path

ROOT = Path.cwd() / "sensor-qa-output"


def seeded_noise(n, seed=20261114):
    out = []
    for _ in range(n):
        total = 0
        for _ in range(12):
            seed = (1664525 * seed + 1013904223) % 4294967296
            total += seed / 4294967296
        out.append(total - 6)
    return out


def moving_average(x, w):
    return [sum(x[max(0, i - w + 1) : i + 1]) / min(w, i + 1) for i in range(len(x))]


def slope(t, y):
    xm = statistics.mean(t)
    ym = statistics.mean(y)
    return sum((a - xm) * (b - ym) for a, b in zip(t, y, strict=True)) / sum(
        (a - xm) ** 2 for a in t
    )


def checks(t, reference, y):
    err = [a - b for a, b in zip(y, reference, strict=True)]
    rough = statistics.stdev([b - a for a, b in pairwise(err)]) / math.sqrt(2)
    mean = statistics.mean(err)
    trend = slope(t, err)
    return {
        "roughness_c": rough,
        "mean_error_c": mean,
        "drift_c_per_s": trend,
        "roughness_flag": rough > 0.4,
        "reference_offset_flag": abs(mean) > 1,
        "reference_drift_flag": abs(trend) > 0.02,
    }


def build():
    t = [i / 10 for i in range(601)]
    noise = seeded_noise(len(t))
    reference = [20 + 2 * (1 - math.cos(math.pi * x / 60)) / 2 for x in t]
    cases = {}
    for name in ["noise", "bias", "drift", "spike", "flatline"]:
        x = [
            v
            + (0.8 if name == "noise" else 0.03) * n
            + (5 if name == "bias" else 0)
            + (0.06 * s if name == "drift" else 0)
            for v, n, s in zip(reference, noise, t, strict=True)
        ]
        if name == "spike":
            x[400] += 8
        if name == "flatline":
            x[250:321] = [x[249]] * 71
        c = checks(t, reference, x)
        detect = []
        if c["roughness_flag"]:
            detect.append("roughness")
        if c["reference_offset_flag"]:
            detect.append("reference offset")
        if c["reference_drift_flag"]:
            detect.append("reference drift")
        cases[name] = {
            "raw": x,
            "average": moving_average(x, 21),
            "checks": c,
            "detected": detect,
            "missed": [] if detect else [name],
        }
    constant = [25 + 0.8 * n for n in noise[:100]]
    return {
        "schema": 1,
        "assumptions": [
            "Synthetic data, not measurements.",
            "Reference treated as exact for this teaching example. "
            "Real references have uncertainty.",
            "60 seconds sampled at 10 Hz; noise deterministic, approximately Gaussian.",
            "Trailing moving average can introduce lag; it does not establish accuracy.",
            "Simple illustrative thresholds; non-detection is not proof of correctness.",
        ],
        "thresholds": {"roughness_c": 0.4, "mean_error_c": 1, "drift_c_per_s": 0.02},
        "t": t,
        "reference": reference,
        "noise": noise,
        "cases": cases,
        "opening": {
            "reference": 20,
            "samples": constant,
            "running_mean": moving_average(constant, 100),
            "mean": statistics.mean(constant),
        },
    }


if __name__ == "__main__":
    ROOT.mkdir(parents=True, exist_ok=True)
    data = build()
    (ROOT / "results.json").write_text(json.dumps(data, indent=1))
    (ROOT / "data.js").write_text(
        "window.SENSOR_DATA=" + json.dumps(data, separators=(",", ":")) + ";"
    )
    with (ROOT / "fault-table.csv").open("w") as f:
        w = csv.writer(f)
        w.writerow(
            [
                "Fault added",
                "Roughness alone",
                "With reference checks",
                "Fault missed",
                "Roughness C",
                "Mean error C",
                "Drift C/s",
            ]
        )
        for name, x in data["cases"].items():
            c = x["checks"]
            w.writerow(
                [
                    name,
                    "flagged" if c["roughness_flag"] else "missed",
                    "; ".join(x["detected"]) or "not flagged",
                    "; ".join(x["missed"]) or "none in this case",
                    c["roughness_c"],
                    c["mean_error_c"],
                    c["drift_c_per_s"],
                ]
            )
    assert abs(data["cases"]["bias"]["checks"]["mean_error_c"] - 5) < 0.1
    assert not data["cases"]["bias"]["checks"]["roughness_flag"]
    assert data["cases"]["drift"]["checks"]["reference_drift_flag"]
    print((ROOT / "fault-table.csv").read_text())
