"""Check that assets/deepcq.js (the in-browser port) matches the Python package.

Runs the site's demo memory through both implementations for the demo's
suggested queries plus randomly generated ones (words from the memory,
stopwords, numbers, percentages, quoted phrases, identifiers) and compares
section scores, included/excluded sections, fallback, content and reduction.

Run from the repo root:  python benchmarks/parity_check.py   (needs node + deepcq)
"""
import json
import random
import re
import subprocess
import sys
from pathlib import Path

from deepcq import DeepCQ, MemorySchema
from deepcq.tokens import _STOPWORDS

ROOT = Path(__file__).resolve().parent.parent
N_RANDOM = 1500
random.seed(11)

demo = json.loads(subprocess.check_output(
    ["node", "-e", f"process.stdout.write(JSON.stringify(require({json.dumps(str(ROOT / 'assets/demo-memory.js'))})))"]))
mem = demo["memory"]


def build():
    cq = DeepCQ(MemorySchema(sections=demo["sections"], keywords=demo["keywords"]))
    for k, v in mem["state"].items():
        cq.state.set(k, v)
    for k, v in mem["cache"].items():
        cq.cache.put(k, v)
    for role, text in mem["history"]:
        cq.history.add(role, text)
    for k, entries in mem["notes"].items():
        for e in entries:
            cq.notes.append(k, e)
    for k, v in mem["reference"].items():
        cq.reference.set(k, v)
    return cq


corpus = " ".join([*mem["state"].values(), *[e for es in mem["notes"].values() for e in es]])
words = re.findall(r"[A-Za-z][A-Za-z0-9-]*|\d+(?:\.\d+)?%?", corpus)
extras = ["big", "picture", "usual", "stuff", "spikes", "running", "1.18", "44%", "v2.3.1", "10b5-1",
          "'export controls'", '"gross margin"', "N7", "Q3", "⚠️", "ESG", "dividends", "guidance?"]
stop = sorted(_STOPWORDS)
queries = list(demo["suggestions"])
for _ in range(N_RANDOM):
    n = random.randint(1, 8)
    q = [random.choice(words) if random.random() < 0.6 else random.choice(stop + extras) for _ in range(n)]
    queries.append(" ".join(q) + random.choice(["", "?", "!"]))

cq = build()
py = []
for q in queries:
    r = cq.query(q)
    py.append({"intent": r.intent, "included": r.sections_included, "excluded": r.sections_excluded,
               "content": r.content, "reduction": r.metrics.reduction_pct,
               "original": r.metrics.original_chars, "filtered": r.metrics.filtered_chars})

js_src = f"""
const D = require({json.dumps(str(ROOT / 'assets/deepcq.js'))});
const M = require({json.dumps(str(ROOT / 'assets/demo-memory.js'))});
const schema = new D.MemorySchema({{sections: M.sections, keywords: M.keywords}});
const qs = JSON.parse(require('fs').readFileSync(0, 'utf8'));
process.stdout.write(JSON.stringify(qs.map(q => {{
  const r = D.query(schema, M.memory, q);
  return {{intent: r.intent, included: r.included, excluded: r.excluded, content: r.content,
          reduction: r.reductionPct, original: r.originalChars, filtered: r.filteredChars}};
}})));
"""
js = json.loads(subprocess.run(["node", "-e", js_src], input=json.dumps(queries), capture_output=True,
                               text=True, check=True).stdout)

mismatches = []
for q, a, b in zip(queries, py, js):
    problems = []
    if a["included"] != b["included"] or a["excluded"] != b["excluded"]:
        problems.append(f"sections py={a['included']} js={b['included']}")
    for s in demo["sections"]:
        if abs(a["intent"][s] - b["intent"][s]) > 1.5e-4:
            problems.append(f"score[{s}] py={a['intent'][s]} js={b['intent'][s]}")
    if a["content"] != b["content"]:
        problems.append("content differs")
    if a["original"] != b["original"] or a["filtered"] != b["filtered"] or abs(a["reduction"] - b["reduction"]) > 0.11:
        problems.append(f"metrics py={a['original']}/{a['filtered']} js={b['original']}/{b['filtered']}")
    if problems:
        mismatches.append((q, problems))

fallbacks = sum(1 for a in py if a["reduction"] == 0.0 and len(a["included"]) == len(demo["sections"]))
print(f"queries: {len(queries)}  mismatches: {len(mismatches)}  python fallbacks: {fallbacks}")
for q, p in mismatches[:15]:
    print(f"  {q!r}: {'; '.join(p)}")
sys.exit(1 if mismatches else 0)
