"""Can document search find every matter that answers a question?

Runs keyword search, embeddings and the two combined on part of the Firm
Knowledge tasks in Harvey LAB (MIT licence, (c) 2026 Harvey AI):
https://github.com/harveyai/harvey-labs

This scores search results only. It is not a LAB score: there is no agent, no
judge and no written answer.

    pip install numpy
    OPENAI_API_KEY=... python3 matter_search_test.py path/to/harvey-labs

It writes docs.npy, index.db and results.json to the current folder. docs.npy
holds the document embeddings, which cost about $0.25 to make in our run.
Delete it if the benchmark's documents change.
"""
import collections, email, glob, html, json, os, re, sqlite3, sys, time, urllib.request, zipfile
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from email import policy

import numpy as np

BENCH = sys.argv[1] if len(sys.argv) > 1 else "harvey-labs"
ROOT = os.path.join(BENCH, "tasks/firm-knowledge/dms/matters")
tag = re.compile(r"<[^>]+>")
def xml_text(x, para):
    x = re.sub(para, "\n", x)
    return html.unescape(tag.sub("", x))
def read(path):
    ext = path.rsplit(".", 1)[-1].lower()
    try:
        if ext == "eml":
            m = email.message_from_binary_file(open(path, "rb"), policy=policy.default)
            body = m.get_body(preferencelist=("plain", "html"))
            t = body.get_content() if body else ""
            return f"{m['subject'] or ''}\n{m['from'] or ''} {m['to'] or ''}\n{tag.sub(' ', t)}"
        z = zipfile.ZipFile(path)
        names = z.namelist()
        if ext == "docx":
            parts = [n for n in names if re.fullmatch(r"word/(document|header\d*|footer\d*|footnotes)\.xml", n)]
            return "\n".join(xml_text(z.read(n).decode("utf8", "ignore"), r"</w:p>|</w:tc>|<w:tab/>") for n in sorted(parts))
        if ext == "pptx":
            parts = [n for n in names if re.fullmatch(r"ppt/slides/slide\d+\.xml", n)]
            return "\n".join(xml_text(z.read(n).decode("utf8", "ignore"), r"</a:p>") for n in sorted(parts))
        if ext == "xlsx":
            out = []
            if "xl/sharedStrings.xml" in names: out.append(xml_text(z.read("xl/sharedStrings.xml").decode("utf8", "ignore"), r"</si>"))
            for n in sorted(n for n in names if re.fullmatch(r"xl/worksheets/sheet\d+\.xml", n)):
                x = z.read(n).decode("utf8", "ignore")
                out.append("\n".join(html.unescape(v) for v in re.findall(r"<is><t[^>]*>(.*?)</t></is>", x)))
            return "\n".join(out)
    except Exception as e:
        return f"__ERROR__ {type(e).__name__}"
    return ""
def job(rel):
    t = re.sub(r"[ \t\r]+", " ", read(os.path.join(ROOT, rel)))
    return {"path": rel, "matter": rel.split("/")[0], "text": re.sub(r"\n\s*\n+", "\n", t).strip()}


# Which matters answer each task, taken from the benchmark's own scoring rules.
M = re.compile(r"\b\d{4}-\d{5}\b")
def load(root):
    out, skipped = [], {"no exact list": 0, "criteria disagree": 0}
    for f in sorted(glob.glob(f"{root}/tasks/*/task.json")):
        t = json.load(open(f))
        exact = [c for c in t["criteria"] if "outside this list:" in c["match_criteria"]]
        if len(exact) != 1:
            skipped["no exact list"] += 1; continue
        body = exact[0]["match_criteria"].split("outside this list:", 1)[1]
        required_text, _, optional_text = body.partition("Additionally")
        required = set(M.findall(required_text))
        optional = set(M.findall(optional_text)) - required
        # Any other criterion that names a matter should name a listed one.
        named = {m for c in t["criteria"] if c is not exact[0] for m in M.findall(c["title"] + " " + c["match_criteria"])}
        if not required or not named <= (required | optional):
            skipped["criteria disagree"] += 1; continue
        out.append({"id": t["id"], "title": t["title"], "question": t["instructions"], "required": sorted(required), "optional": sorted(optional)})
    return out, skipped


def main():
    K = [10, 20, 50]
    tasks, skipped = load(os.path.join(BENCH, "tasks/firm-knowledge"))
    print("skipped:", skipped)
    files = sorted(os.path.relpath(os.path.join(d, f), ROOT) for d, _, fs in os.walk(ROOT) for f in fs if not f.startswith("."))
    with ProcessPoolExecutor() as ex: docs = list(ex.map(job, files, chunksize=32))
    bad = [d["path"] for d in docs if not d["text"] or d["text"].startswith("__ERROR__")]
    if bad: raise SystemExit(f"{len(bad)} documents could not be read, for example {bad[0]}")
    matters = sorted({d["matter"] for d in docs}); print(len(docs), "documents,", len(matters), "matters,", len(tasks), "questions", flush=True)
    STOP = set("a an and any are as at be been before but by can could did do does each every for from get give had has have help how i i'm i'd if in into is it its just last let like list look make me most my need of on one or our ours pull put putting please see set show so some tell than that the their them there these they this those to up us use used want was we we've we're were what when where which who whose why will with would you your matter matters firm firm's across all also".split())

    # 1. Keyword search: SQLite FTS5's BM25 over the path and full text.
    t0 = time.time(); db = sqlite3.connect("index.db"); db.execute("PRAGMA journal_mode=OFF"); db.execute("DROP TABLE IF EXISTS d")
    db.execute("CREATE VIRTUAL TABLE d USING fts5(path, body, tokenize='porter unicode61')")
    db.executemany("INSERT INTO d(rowid, path, body) VALUES (?,?,?)", ((i, re.sub(r"[-_/.]", " ", d["path"].split("/", 1)[1]), d["text"]) for i, d in enumerate(docs))); db.commit()
    print(f"keyword index built in {time.time()-t0:.0f}s", flush=True)
    def keyword(q):
        terms = [w for w in dict.fromkeys(re.findall(r"[a-z0-9']+", q.lower().replace("’", "'"))) if w not in STOP and len(w) > 1]
        rows = db.execute("SELECT rowid FROM d WHERE d MATCH ? ORDER BY bm25(d) LIMIT 9288", (" OR ".join('"%s"' % w.replace('"', "") for w in terms),)).fetchall()
        return [r[0] for r in rows]

    # 2. Embeddings of each document's path and first 6,000 characters.
    key = os.environ["OPENAI_API_KEY"]
    used = 0
    def embed(batch):
        nonlocal used
        for attempt in range(8):
            try:
                r = urllib.request.Request("https://api.openai.com/v1/embeddings", data=json.dumps({"model": "text-embedding-3-small", "input": batch}).encode(), headers={"authorization": f"Bearer {key}", "content-type": "application/json"})
                body = json.loads(urllib.request.urlopen(r, timeout=120).read()); used += body["usage"]["total_tokens"]
                return [x["embedding"] for x in sorted(body["data"], key=lambda x: x["index"])]
            except Exception as e:
                print("retry", type(e).__name__, getattr(e, "code", ""), flush=True); time.sleep(5 * (attempt + 1))
        raise SystemExit("embedding failed")
    if not os.path.exists("docs.npy"):
        texts = [(d["path"].split("/", 1)[1] + "\n" + d["text"])[:6000] for d in docs]
        batches = [texts[i:i+100] for i in range(0, len(texts), 100)]
        with ThreadPoolExecutor(4) as ex: V = np.array([v for b in ex.map(embed, batches) for v in b], dtype=np.float32)
        np.save("docs.npy", V)
    V = np.load("docs.npy"); V /= np.linalg.norm(V, axis=1, keepdims=True)
    Q = np.array([v for i in range(0, len(tasks), 100) for v in embed([t["question"] for t in tasks[i:i+100]])], dtype=np.float32); Q /= np.linalg.norm(Q, axis=1, keepdims=True)
    print("embedding tokens this run:", used, f"(about ${used*0.02/1e6:.2f} at $0.02 per million)", flush=True)

    # einsum in float64: NumPy's matmul printed overflow warnings on macOS.
    V, Q = V.astype(np.float64), Q.astype(np.float64)
    assert np.isfinite(V).all() and np.isfinite(Q).all()
    def scores(q):
        s = np.einsum("ij,j->i", V, q)
        assert np.isfinite(s).all() and abs(s).max() <= 1.000001
        return s

    def to_matters(doc_ids):
        return list(dict.fromkeys(docs[i]["matter"] for i in doc_ids))   # a matter ranks where its best document does
    def fuse(a, b):
        s = collections.defaultdict(float)
        for ranking in (a, b):
            for r, m in enumerate(ranking): s[m] += 1 / (60 + r + 1)
        return sorted(s, key=lambda m: (-s[m], m))

    rows = []
    for i, t in enumerate(tasks):
        kw = to_matters(keyword(t["question"])); em = to_matters(np.argsort(-scores(Q[i]), kind="stable").tolist())
        ranked = {"keyword": kw, "embeddings": em, "combined": fuse(kw, em)}
        req = set(t["required"]); row = {**{k: t[k] for k in ("id", "title", "question")}, "required": t["required"]}
        for name, order in ranked.items():
            pos = {m: r + 1 for r, m in enumerate(order)}
            row[name] = {"ranks": {m: pos.get(m) for m in t["required"]}, **{f"found@{k}": len(req & set(order[:k])) for k in K}}
        rows.append(row)
    json.dump(rows, open("results.json", "w"), indent=1)
    def summary(sel, label):
        n = len(sel); total = sum(len(r["required"]) for r in sel); print(f"\n{label}: {n} questions, {total} qualifying matters")
        for m in ("keyword", "embeddings", "combined"):
            print(f"  {m:10}", " | ".join(f"top {k}: {100*sum(r[m][f'found@{k}'] for r in sel)/total:.0f}% of matters, {sum(r[m][f'found@{k}']==len(r['required']) for r in sel)}/{n} questions complete" for k in K))
    summary(rows, "ALL")
    summary([r for r in rows if len(r["required"]) <= 1], "ONE ANSWER"); summary([r for r in rows if 2 <= len(r["required"]) <= 10], "2 TO 10 ANSWERS"); summary([r for r in rows if len(r["required"]) > 10], "MORE THAN 10")


if __name__ == "__main__":
    main()
