"""Guards for ../widget.html: its data block, its size, and that its JavaScript computes what kernel_fusion.py does."""
import json
import re
import subprocess

import kernel_fusion as kf
from embed_widget import WIDGET, embed

HTML = WIDGET.read_text(encoding="utf-8")

# Reads the number code out of the widget between its marker comments, runs it, and compares with the values Python wrote into the fixture.
PARITY = r"""
import fs from 'node:fs';
const [fixture, widget] = process.argv.slice(2);
const fx = JSON.parse(fs.readFileSync(fixture, 'utf8'));
const html = fs.readFileSync(widget, 'utf8');
const DATA = JSON.parse(html.match(/<script type="application\/json" id="fus-data">([\s\S]*?)<\/script>/)[1]);
const js = html.slice(html.indexOf('/* ---------- the numbers'), html.indexOf('/* ---------- the page'));
const api = new Function('DATA', "'use strict';" + js + '; return {chainBytes, chainTime, matmulTime, totalBytes, totalTime};')(DATA);
const bad = [];
const close = (a, b) => Math.abs(a - b) <= 1e-12 * Math.abs(b);
fx.cases.forEach((c) => {
  if (api.totalBytes(c.steps, c.fused, c.mm) !== c.bytes) bad.push(['bytes', c]);
  if (!close(api.totalTime(c.steps, c.fused, c.mm), c.time)) bad.push(['time', c, api.totalTime(c.steps, c.fused, c.mm)]);
});
if (!close(api.matmulTime(), fx.matmul)) bad.push(['matmul', api.matmulTime(), fx.matmul]);
console.log(JSON.stringify({ cases: fx.cases.length, bad: bad.slice(0, 5) }));
process.exit(bad.length ? 1 : 0);
"""


def test_widget_data_block_matches_kernel_fusion():
    """Guards an edit to the constants that was not copied into the widget (run embed_widget.py)."""
    assert embed(HTML) == HTML


def test_every_element_the_script_looks_up_exists():
    """Guards a widget that never starts: a lookup of an id the page does not contain throws in the browser."""
    page = HTML[:HTML.index("<script")]
    ids = set(re.findall(r"\$\('([\w-]+)'\)", HTML[HTML.index("<script>"):])) | {"fus-t0", "fus-t1", "fus-s0", "fus-s1", "fus-mmbar0", "fus-mmbar1", "fus-b0", "fus-b1"}
    assert all(f'id="{i}"' in page for i in ids), sorted(i for i in ids if f'id="{i}"' not in page)
    assert 'id="fus-data"' in HTML and 'class="fus-root"' in page


def test_widget_is_small_and_asks_for_nothing_online():
    """Guards the widget growing past the 300-line limit, or reaching the network (a fetch, an external script or a font) and breaking offline use."""
    assert len(HTML.encode("utf-8")) < 40 * 1024 and HTML.count("\n") < 300
    for banned in ("http://", "https://", "fetch(", "XMLHttpRequest", "WebSocket", "sendBeacon", "import("):
        assert banned not in HTML, banned
    assert " src=" not in HTML and "@import" not in HTML


def test_widget_numbers_match_the_python_code(tmp_path):
    """Guards the widget's JavaScript drifting from kernel_fusion.py: its bytes and predicted times for every slider position,
    with and without the multiply, must be the lesson's."""
    cases = [{"steps": k, "fused": f, "mm": mm,
              "bytes": kf.matmul_then_chain_bytes(k, f) if mm else kf.chain_bytes(k, f),
              "time": kf.matmul_then_chain_time(k, f) if mm else kf.chain_time(k, f)}
             for k in range(1, kf.MAX_STEPS + 1) for f in (False, True) for mm in (False, True)]
    (tmp_path / "fixture.json").write_text(json.dumps({"matmul": kf.matmul_time(), "cases": cases}), encoding="utf-8")
    (tmp_path / "parity.mjs").write_text(PARITY, encoding="utf-8")
    run = subprocess.run(["node", str(tmp_path / "parity.mjs"), str(tmp_path / "fixture.json"), str(WIDGET)],
                         capture_output=True, text=True, timeout=120)
    assert run.returncode == 0, run.stdout + run.stderr
    assert json.loads(run.stdout)["cases"] == kf.MAX_STEPS * 2 * 2 == 32
    assert kf.matmul_then_chain_bytes(3, False) - kf.matmul_then_chain_bytes(3, True) == kf.chain_bytes(3, False)
