#!/usr/bin/env python3
"""What finds the right note? Take a memory search apart on your own notes.

Rebuilds the keyword search Notesmith and AgentScribe use, then turns its parts on one at a time
and reports where the right note lands for each of your searches. Python's own sqlite3 and its
full text search (FTS5), nothing to install, and nothing leaves your Mac.

    python3 -B memory-search-check.py NOTES SEARCHES OUT

NOTES     a folder of .md or .txt notes. Subfolders are stores (for example your notes in one and
          an AI's notes in another); with only one, the "each store on its own" rows are skipped.
          A note whose first line starts with "# " uses that line as its title.
SEARCHES  a text file, one search per line: the search, a tab, then the answer note's path inside
          NOTES (several answers separated by ";"), and optionally a tab and a set name, so a set
          kept back from any decision can be reported on its own.
OUT       a folder for summary.csv (one row per setup and set) and ranks.csv (where the answer
          landed for each search line, 1 to 20, blank when it was not in the top 20). Neither file
          holds a search or a note's text, so both can be shared.

The setups, in order:
  1 per-store            each store searched on its own, whole notes, title weighted 10 to 1,
                         results merged by score
  2 per-store-stem       the same, with stemming (porter: "decisions" also matches "decision")
  3 per-store-sections   the same as 1, notes cut into sections of about 800 characters
  4 one-list-stem        one list over every store, sections, stemming (AgentScribe 2.0.3)
  5 one-list             one list over every store, sections, no stemming
  6 notesmith            5, with words of one or two letters matched exactly and identical notes
                         kept apart (Notesmith 1.0.1 and later)
Every setup drops common words, matches each word as a prefix, and merges two lists (sections with
any of the words, sections with all of them) by reciprocal rank: 1 / (60 + place) from each list.
"""
from __future__ import annotations

import csv
import hashlib
import json
import pathlib
import platform
import re
import sqlite3
import sys

# AgentScribe's and Notesmith's stopwords, verbatim.
STOPWORDS = set("""the and for are but not you all any can had her was one our out has his how its who did get she too
use with that this from have what when where which does into about your they them then than there their will would
could should been being were his him her is it in on of to as at by an be or if do so we my me no up""".split())
SETUPS = ("per-store", "per-store-stem", "per-store-sections", "one-list-stem", "one-list", "notesmith")


def words(search: str) -> list[str]:
    """Lowercased, split on anything not a letter or digit, longer than one character, no stopwords, at most 12."""
    return [w for w in re.split(r"[^\w]|_", search.lower()) if len(w) > 1 and w not in STOPWORDS][:12]


def pattern(ws: list[str], joiner: str, exact_short: bool) -> str | None:
    if not ws or (joiner == " " and len(ws) < 2):
        return None
    return joiner.join(f'"{w}"' if exact_short and len(w) < 3 else f'"{w}"*' for w in ws)


def sections(body: str, limit: int = 800) -> list[str]:
    """Paragraphs packed into sections of at most `limit` characters; a longer paragraph is cut at words."""
    out, current = [], ""
    for para in body.split("\n\n"):
        p = para.strip()
        if not p:
            continue
        if len(p) > limit:
            if current:
                out.append(current); current = ""
            piece = ""
            for word in [w for w in p.split(" ") if w]:
                if len(piece) + len(word) + 1 > limit:
                    out.append(piece); piece = ""
                piece += word if not piece else " " + word
            if piece:
                out.append(piece)
        elif len(current) + len(p) + 2 > limit:
            if current:
                out.append(current)
            current = p
        else:
            current += p if not current else "\n\n" + p
    if current:
        out.append(current)
    return out or [body]


class Index:
    """One FTS5 table: a row per section, or a row per note with title and body columns."""

    def __init__(self, docs: list[dict], tokenizer: str, by_section: bool):
        self.db = sqlite3.connect(":memory:")
        self.by_section = by_section
        if by_section:
            self.db.execute(f"CREATE VIRTUAL TABLE f USING fts5(doc UNINDEXED, text, tokenize='{tokenizer}')")
            self.db.executemany("INSERT INTO f(doc, text) VALUES(?,?)", [(d["doc"], s) for d in docs for s in sections(d["text"])])
        else:
            self.db.execute(f"CREATE VIRTUAL TABLE f USING fts5(doc UNINDEXED, title, body, tokenize='{tokenizer}')")
            self.db.executemany("INSERT INTO f(doc, title, body) VALUES(?,?,?)", [(d["doc"], d["title"], d["body"]) for d in docs])

    def ranked(self, pat: str | None, limit: int) -> list[tuple[int, float]]:
        """Distinct notes, best bm25 first, each with its best bm25."""
        if not pat:
            return []
        rank = "bm25(f)" if self.by_section else "bm25(f, 0.0, 10.0, 1.0)"
        try:
            rows = self.db.execute(f"SELECT doc, {rank} FROM f WHERE f MATCH ? ORDER BY {rank} LIMIT ?", (pat, limit)).fetchall()
        except sqlite3.OperationalError:
            return []
        seen, out = set(), []
        for doc, score in rows:
            if doc not in seen:
                seen.add(doc); out.append((doc, score))
        return out


def fused(index: Index, search: str, exact_short: bool = False) -> list[tuple[int, float, float]]:
    """(note, fused score, best bm25), best first: any-word list (60) and every-word list (30), 1 / (60 + place) each."""
    ws = words(search)
    score: dict[int, float] = {}
    best: dict[int, float] = {}
    for lst in (index.ranked(pattern(ws, " OR ", exact_short), 60), index.ranked(pattern(ws, " ", exact_short), 30)):
        for place, (doc, b) in enumerate(lst):
            score[doc] = score.get(doc, 0) + 1 / (60 + place + 1)
            best[doc] = min(best.get(doc, b), b)
    return sorted(((d, score[d], best[d]) for d in sorted(score)), key=lambda t: -t[1])


def per_store(indexes: list[Index], search: str) -> list[int]:
    """Each store ranked on its own, then one list by fused score; a tie goes to the stronger bm25, then the first store."""
    rows = [(-s, b, i, doc) for i, idx in enumerate(indexes) for doc, s, b in fused(idx, search)]
    return [doc for *_, doc in sorted(rows)]


def read_notes(root: pathlib.Path) -> list[dict]:
    notes = []
    for path in sorted(p for p in root.rglob("*") if p.suffix in (".md", ".txt") and p.is_file()):
        rel = path.relative_to(root).as_posix()
        content = path.read_text(encoding="utf-8", errors="replace").replace("\r\n", "\n")
        title, body = "", content
        if content.startswith("# "):
            first, _, rest = content.partition("\n")
            title, body = first[2:], rest[1:] if rest.startswith("\n") else rest
        notes.append({"path": rel, "store": rel.split("/")[0] if "/" in rel else "", "title": title, "body": body,
                      "text": body if not title else title if not body else f"{title}\n\n{body}"})
    return notes


def main() -> int:
    if len(sys.argv) != 4:
        sys.exit(__doc__)
    root, searches_file, out = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3])
    notes = read_notes(root)
    by_path = {n["path"]: i for i, n in enumerate(notes)}
    searches = []
    for line_no, line in enumerate(searches_file.read_text(encoding="utf-8").splitlines(), 1):
        if not line.strip():
            continue
        parts = line.split("\t")
        answers = {a.strip() for a in parts[1].split(";") if a.strip()} if len(parts) > 1 else set()
        missing = answers - by_path.keys()
        if not answers or missing:
            sys.exit(f"{searches_file}:{line_no}: answer not found in {root}: {sorted(missing) or 'none given'}")
        searches.append({"line": line_no, "text": parts[0], "answers": {by_path[a] for a in answers},
                         "set": parts[2].strip() if len(parts) > 2 and parts[2].strip() else "all"})

    # Identical notes become one, as AgentScribe stores them; Notesmith keeps every note.
    merged, members, seen = [], {}, {}
    for i, n in enumerate(notes):
        h = hashlib.sha256(" ".join(n["text"].lower().split()).encode()).hexdigest()
        if h not in seen:
            seen[h] = len(merged)
            merged.append(dict(n, doc=len(merged)))
            members[seen[h]] = set()
        members[seen[h]].add(i)
    each = [dict(n, doc=i) for i, n in enumerate(notes)]
    stores = sorted({n["store"] for n in notes})
    per = {(tok, sec): [Index([d for d in merged if d["store"] == s], tok, sec) for s in stores]
           for tok, sec in (("unicode61", False), ("porter unicode61", False), ("unicode61", True))}
    one_stem, one = Index(merged, "porter unicode61", True), Index(merged, "unicode61", True)
    ns = Index(each, "unicode61", True)
    run = {
        "per-store": lambda q: per_store(per[("unicode61", False)], q),
        "per-store-stem": lambda q: per_store(per[("porter unicode61", False)], q),
        "per-store-sections": lambda q: per_store(per[("unicode61", True)], q),
        "one-list-stem": lambda q: [d for d, *_ in fused(one_stem, q)],
        "one-list": lambda q: [d for d, *_ in fused(one, q)],
        "notesmith": lambda q: [d for d, *_ in fused(ns, q, exact_short=True)],
    }
    setups = [s for s in SETUPS if len(stores) > 1 or not s.startswith("per-store")]

    def landed(order: list[int], answers: set[int], kept_apart: bool) -> int | None:
        for place, doc in enumerate(order[:20], 1):
            if ({doc} if kept_apart else members[doc]) & answers:
                return place
        return None

    for s in searches:
        for name in setups:
            s[name] = landed(run[name](s["text"]), s["answers"], name == "notesmith")

    out.mkdir(parents=True, exist_ok=True)
    with open(out / "ranks.csv", "w", encoding="utf-8", newline="") as f:
        w = csv.writer(f)
        w.writerow(["line", "set"] + setups)
        for s in searches:
            w.writerow([s["line"], s["set"]] + [s[n] or "" for n in setups])
    rows = []
    for set_name in sorted({s["set"] for s in searches}):
        group = [s for s in searches if s["set"] == set_name]
        for name in setups:
            ranks = [s[name] for s in group]
            rows.append({"set": set_name, "setup": name, "searches": len(group), "first": sum(1 for r in ranks if r == 1),
                         "top_8": sum(1 for r in ranks if r and r <= 8), "top_20": sum(1 for r in ranks if r),
                         "mrr": f"{sum(1 / r for r in ranks if r) / len(group):.4f}"})
    with open(out / "summary.csv", "w", encoding="utf-8", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0]))
        w.writeheader(); w.writerows(rows)
    (out / "run.json").write_text(json.dumps({
        "notes": len(notes), "merged_notes": len(merged), "stores": len(stores), "searches": len(searches),
        "python": platform.python_version(), "sqlite": sqlite3.sqlite_version,
        "searches_sha256": hashlib.sha256(searches_file.read_bytes()).hexdigest()}, indent=1) + "\n")
    print(f"{len(notes)} notes ({len(merged)} after merging identical ones) in {len(stores)} store(s), {len(searches)} searches")
    print(f"{'set':10} {'setup':20} {'first':>6} {'top 8':>6} {'MRR':>7}")
    for r in rows:
        print(f"{r['set']:10} {r['setup']:20} {r['first']:>6} {r['top_8']:>6} {r['mrr']:>7}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
