"""Guards for ../widget.html: its data block, its size, that its JavaScript ranks and scores like embed_search.py, and what a reader sees."""
# guards: new lesson tool; the widget copies the toy's numbers and steps into JavaScript, so a toy edit left out of widget.html, or JavaScript
# that ranks differently from Python, would show the reader numbers the lesson text does not print
import json
import re
import subprocess

import embed_search as es
from embed_widget import CONFIG_BLOCK, WIDGET, embed

HTML = WIDGET.read_text(encoding="utf-8")
ROOT = HTML[HTML.index('<div class="srch-root">'):HTML.index("<script")]
TOLERANCE = 1e-12                                   # the JavaScript and Python scores may differ by at most this much
MODES = ("words", "meaning", "cell")
VECTORS = [es.embed(d) for d in es.DOCS]

# Reads the steps out of the widget between its marker comments, runs them with Node, and compares every embedding (within 1e-12), and the
# order, shared words, score and compared-or-not flag of every row (exact, and within 1e-12 for the score), for every question and way of searching.
PARITY = r"""
import fs from 'node:fs';
const [fixture, widget, tolerance] = process.argv.slice(2);
const fx = JSON.parse(fs.readFileSync(fixture, 'utf8'));
const html = fs.readFileSync(widget, 'utf8');
const cfg = JSON.parse(html.match(/<script type="application\/json" id="srch-config">([\s\S]*?)<\/script>/)[1]);
const js = html.slice(html.indexOf('/* ---------- the model ('), html.indexOf('/* ---------- display'));
const api = new Function('cfg', "'use strict';" + js + '; return {embed: embed, rank: rank};')(cfg);
const tol = Number(tolerance), bad = [];
let checks = 0, worst = 0;
const near = (a, b) => { const d = Math.abs(a - b); worst = Math.max(worst, d); return d <= tol; };
fx.embeds.forEach(([text, want]) => {
  const got = api.embed(text);
  want.forEach((x, t) => { checks++; if (!near(got[t], x)) bad.push(['embed', text, t, got[t], x]); });
});
Object.keys(fx.ranks).forEach((key) => {
  const [qi, mode] = key.split('|'), got = api.rank(Number(qi), mode), want = fx.ranks[key];
  checks++;
  if (got.length !== want.length) { bad.push(['length', key]); return; }
  want.forEach((w, k) => {
    checks++;
    const g = got[k];
    if (g.i !== w.i || g.checked !== w.checked || JSON.stringify(g.shared) !== JSON.stringify(w.shared) || !near(g.score, w.score)) bad.push(['row', key, k, g, w]);
  });
});
console.log(JSON.stringify({ checks, worst, bad: bad.slice(0, 4) }));
process.exit(bad.length ? 1 : 0);
"""

# Runs the page script against a small stand-in for the DOM, presses every question and every way of searching, and reads back what a reader sees.
PAGE = r"""
import fs from 'node:fs';
const [widget, fixture] = process.argv.slice(2);
const html = fs.readFileSync(widget, 'utf8');
const fx = JSON.parse(fs.readFileSync(fixture, 'utf8'));
const config = html.match(/<script type="application\/json" id="srch-config">([\s\S]*?)<\/script>/)[1];
const code = html.match(/<script>([\s\S]*?)<\/script>/)[1];

function el(tag) {
  const e = { tag, children: [], listeners: {}, style: {}, attrs: {}, textContent: '' };
  e.setAttribute = (k, v) => { e.attrs[k] = v; };
  e.addEventListener = (type, f) => (e.listeners[type] = e.listeners[type] || []).push(f);
  e.appendChild = (c) => (e.children.push(c), c);
  return e;
}
function open() {
  const page = { root: el('html'), messages: [], parent: { other: true } };
  fx.ids.forEach((id) => { page[id] = el('x'); });
  page['srch-config'].textContent = config;
  const doc = { getElementById: (id) => page[id], createElement: el, documentElement: page.root };
  const win = { addEventListener: (type, f) => page.messages.push(f) };
  new Function('document', 'window', 'parent', code)(doc, win, page.parent);
  return page;
}
const fire = (e) => (e.listeners.click || []).forEach((f) => f({ target: e }));
const bad = [];
const want = (what, got, expected) => { if (JSON.stringify(got) !== JSON.stringify(expected)) bad.push([what, got, expected]); };
function look(page, qi, mode, what) {                // compares the page with Python's view of one question and one way of searching
  const v = fx.views[qi + '|' + mode], rows = page['srch-list'].children;
  const summary = page['srch-summary'].textContent;
  want(what + ': summary says', v.fragments.filter((f) => !summary.includes(f)), []);
  want(what + ': question pressed', page['srch-queries'].children.map((b) => b.attrs['aria-pressed']), fx.queries.map((q, k) => String(k === qi)));
  want(what + ': way pressed', page['srch-modes'].children.map((b) => b.attrs['aria-pressed']), fx.modes.map((m) => String(m === mode)));
  want(what + ': sentences in rank order', rows.map((li) => li.children[0].textContent), v.rows.map((r) => r.text));
  want(what + ': value column', rows.map((li) => li.children[1].children[1].textContent), v.rows.map((r) => r.value));
  want(what + ': bar widths', rows.map((li) => Number(parseFloat(li.children[1].children[0].children[0].style.width).toFixed(1))), v.rows.map((r) => Number(r.width.toFixed(1))));
  want(what + ': the best is marked', rows.map((li) => li.attrs['data-top']), v.rows.map((r) => String(r.top)));
  want(what + ': not compared say so', rows.map((li) => li.attrs['data-checked']), v.rows.map((r) => String(r.checked)));
  want(what + ': known words line', page['srch-known'].textContent, v.known);
}

const first = open();
look(first, fx.opening.query, fx.opening.mode, 'opening state');
want('nothing spoken yet', first['srch-live'].textContent, '');
want('question buttons', first['srch-queries'].children.map((b) => b.textContent), fx.queries);
want('way buttons', first['srch-modes'].children.map((b) => b.textContent), fx.labels);
want('note counts sentences and words', first['srch-note'].textContent.includes(fx.note), true);

// every question with every way of searching, by pressing the buttons
const page = open();
fx.queries.forEach((q, qi) => {
  fire(page['srch-queries'].children[qi]);
  fx.modes.forEach((mode, m) => {
    fire(page['srch-modes'].children[m]);
    look(page, qi, mode, q + ' / ' + mode);
    want(q + ' / ' + mode + ': spoken', page['srch-live'].textContent, page['srch-summary'].textContent);
  });
});

// the host page theme: only the parent window may set it, and only to light or dark
const themed = open();
const send = (data, source) => themed.messages.forEach((f) => f({ data, source }));
send({ type: 'spicyshark:theme', theme: 'dark' }, { other: false });
send({ type: 'spicyshark:theme', theme: 'purple' }, themed.parent);
send({ type: 'other', theme: 'dark' }, themed.parent);
send(null, themed.parent);
want('ignored messages', themed.root.attrs, {});
send({ type: 'spicyshark:theme', theme: 'dark' }, themed.parent);
want('theme from the parent', themed.root.attrs, { 'data-theme': 'dark' });
send({ type: 'spicyshark:theme', theme: 'light' }, themed.parent);
want('theme back to light', themed.root.attrs, { 'data-theme': 'light' });

console.log(JSON.stringify({ questions: fx.queries.length, bad: bad.slice(0, 5) }));
process.exit(bad.length ? 1 : 0);
"""


def run_node(tmp_path, script, fixture, args):
    (tmp_path / "fixture.json").write_text(json.dumps(fixture), encoding="utf-8")
    (tmp_path / "check.mjs").write_text(script, encoding="utf-8")
    run = subprocess.run(["node", str(tmp_path / "check.mjs"), *args(tmp_path)], capture_output=True, text=True, timeout=120)
    assert run.returncode == 0, run.stdout + run.stderr
    return json.loads(run.stdout)


def rows_for(qi, mode):
    """Python's answer for one question and way of searching: the rows best first, then the sentences that were not compared, in list order."""
    q = es.QUERIES[qi]
    qv = es.embed(q)
    if mode == "words":
        return [{"i": i, "score": s, "shared": es.shared_words(q, es.DOCS[i]), "checked": True} for i, s in es.rank_keywords(q)]
    checked = set(range(len(es.DOCS))) if mode == "meaning" else set(es.cells_checked(qv, VECTORS, 1))
    ranked = es.nearest(qv, VECTORS, len(es.DOCS))
    return ([{"i": i, "score": s, "shared": [], "checked": True} for i, s in ranked if i in checked]
            + [{"i": i, "score": es.cosine(qv, VECTORS[i]), "shared": [], "checked": False} for i in range(len(es.DOCS)) if i not in checked])


def view_for(qi, mode):
    """What the page should show: each row's sentence, value text, bar width and marks, and fragments the summary line must contain."""
    rows, q = rows_for(qi, mode), es.QUERIES[qi]
    best = rows[0]
    found = best["score"] > 0
    scale = max([1] + [len(es.shared_words(a, d)) for a in es.QUERIES for d in es.DOCS])
    out = []
    for k, r in enumerate(rows):
        if mode == "words":
            value = f"{len(r['shared'])} shared: " + ", ".join(r["shared"]) if r["shared"] else "0 shared"
            width = 100 * r["score"] / scale
        else:
            value = f"{r['score']:.3f}" if r["checked"] else "not compared"
            width = 100 * r["score"] if r["checked"] else 0
        out.append({"text": es.DOCS[r["i"]], "value": value, "width": width, "top": k == 0 and found, "checked": r["checked"]})
    doc = f"“{es.DOCS[best['i']]}”"
    if mode == "words":
        n = best["score"]
        fragments = [f"the top match shares {n} word{'s' if n != 1 else ''}", f"({', '.join(best['shared'])})", doc] if found else ["no sentence shares a word"]
    elif mode == "meaning":
        fragments = [doc, f"closeness {best['score']:.3f}"] if found else ["no word the toy knows"]
    else:
        everything = rows_for(qi, "meaning")[0]
        fragments = [f"compared {sum(r['checked'] for r in rows)} of {len(rows)} sentences"]
        fragments += ([doc, f"closeness {best['score']:.3f}", "also the closest of all" if everything["i"] == best["i"] else "it was not compared"]
                      if found else ["no word the toy knows"])
    known = [w for w in es.content_words(q) if w in es.WORD_VECTORS]
    return {"rows": out, "fragments": fragments, "known": "Words in the question that the toy has numbers for: " + (", ".join(known) or "none") + "."}


# guards: a toy edit that was not copied into widget.html (run embed_widget.py), and an embed that skips a drifted block
def test_widget_data_block_matches_the_python_toy():
    assert embed(HTML) == HTML
    drifted = HTML.replace('"opening": {"query": 0', '"opening": {"query": 1', 1).replace('"Code E4410"', '"Code E4411"', 1)
    assert drifted != HTML and embed(drifted) == HTML


# guards: a widget that never starts: the parity run covers only the formulas, so a misspelt id passes there and throws in the browser
def test_every_element_the_script_looks_up_exists_inside_the_root():
    script = HTML[HTML.index("<script>"):]
    lookups = set(re.findall(r"\$\('([\w-]+)'\)", script))
    missing = sorted(i for i in lookups if i != "srch-config" and f'id="{i}"' not in ROOT)
    assert not missing, missing
    assert 'id="srch-config"' in HTML


# guards: a widget that grows a network call, a form (it cannot submit in the sandboxed frame) or motion (nothing here switches it off)
def test_widget_is_small_and_asks_for_nothing_online():
    assert len(HTML.splitlines()) <= 260 and len(HTML.encode("utf-8")) < 40 * 1024
    page = CONFIG_BLOCK.sub("", HTML)
    for banned in ("http://", "https://", "fetch(", "XMLHttpRequest", "WebSocket", "sendBeacon", "import("):
        assert banned not in page, banned
    assert " src=" not in page and "@import" not in page
    assert "<form" not in HTML and 'type="submit"' not in HTML
    assert "transition" not in HTML and "animation" not in HTML
    assert "<details><summary>More settings</summary>" in ROOT and "<details open" not in ROOT


# guards: a widget that loses the page-theme listener (a white frame on a dark page) or takes a colour outside the site's palette
def test_widget_keeps_the_site_theme_listener_and_palette():
    assert "d.type !== 'spicyshark:theme'" in HTML and "e.source !== parent" in HTML and "parent === window" in HTML
    for pair in ("--bg: light-dark(#ffffff, #0a0f17)", "--panel: light-dark(#ebf0f6, #131b28)", "--ink: light-dark(#0a1626, #f4f7fb)",
                 "--mute: light-dark(#44566b, #a3b1c4)", "--ctl: light-dark(#66768a, #7a8a9f)", "--ink-on: light-dark(#f6f8fb, #05070c)",
                 "--green: light-dark(#00855F, #009E73)", ":root[data-theme=light]", ":root[data-theme=dark]"):
        assert pair in HTML, pair
    assert not set(re.findall(r"#[0-9a-fA-F]{3,8}\b", HTML)) - {"#ffffff", "#0a0f17", "#ebf0f6", "#131b28", "#0a1626", "#f4f7fb", "#44566b", "#a3b1c4",
                                                               "#66768a", "#7a8a9f", "#f6f8fb", "#05070c", "#00855F", "#009E73"}


# guards: the widget's JavaScript drifting from embed_search.py. Every embedding and score must agree within 1e-12 and every order, shared word
# and compared-or-not flag exactly; a toy edit that makes two sentences tie to within rounding shows up here as a different order
def test_widget_steps_rank_and_score_like_the_python_toy(tmp_path):
    fixture = {"embeds": [[t, es.embed(t)] for t in es.DOCS + es.QUERIES],
               "ranks": {f"{qi}|{mode}": rows_for(qi, mode) for qi in range(len(es.QUERIES)) for mode in MODES}}
    result = run_node(tmp_path, PARITY, fixture, lambda d: [str(d / "fixture.json"), str(WIDGET), str(TOLERANCE)])
    assert result["bad"] == [] and result["checks"] == (len(es.DOCS) + len(es.QUERIES)) * len(es.TOPICS) + len(es.QUERIES) * len(MODES) * (1 + len(es.DOCS))
    assert result["worst"] <= TOLERANCE


# guards: what a reader sees: every question and every way of searching shows Python's order, value text and bar widths, the best row is marked
# only when something matched, a sentence that was not compared says so, and the buttons speak
def test_widget_page_shows_what_the_lesson_names(tmp_path):
    opening = json.loads(CONFIG_BLOCK.search(HTML).group(2))["opening"]
    assert opening == es.config()["opening"] and opening["mode"] == "words" and es.QUERIES[opening["query"]] == "Can I get my money back?"
    assert 'class="srch-sr" id="srch-live" role="status" aria-live="polite" aria-atomic="true"' in ROOT
    ids = sorted(set(re.findall(r"\$\('([\w-]+)'\)", HTML[HTML.index("<script>"):])))
    fixture = {"ids": ids, "queries": es.QUERIES, "modes": list(MODES), "labels": ["Words only", "Meaning", "Meaning, one cell"], "opening": opening,
               "note": f"{len(es.DOCS)} sentences and {len(es.WORD_VECTORS)} words",
               "views": {f"{qi}|{mode}": view_for(qi, mode) for qi in range(len(es.QUERIES)) for mode in MODES}}
    result = run_node(tmp_path, PAGE, fixture, lambda d: [str(WIDGET), str(d / "fixture.json")])
    assert result == {"questions": len(es.QUERIES), "bad": []}
