"""Run a five-passage SQLite FTS5 and multilingual E5 retrieval example.

Usage: python transcript_search.py /path/to/multilingual-e5-small
The model directory contains tokenizer.json and onnx/model_quantized.onnx.
Requires Python with SQLite FTS5, numpy, onnxruntime, and tokenizers.
"""

import argparse
import json
import sqlite3
from collections import defaultdict
from pathlib import Path

import numpy as np
import onnxruntime as ort
from tokenizers import Tokenizer

PASSAGES = (
    (1, "08:12", "The supplier raised prices twice before we changed packaging."),
    (2, "12:48", "We raised prices in May after switching to weekly deliveries."),
    (3, "23:16", "The old subscription fee wasn't enough to cover what we spent on every order."),
    (4, "29:54", "We cut delivery fees to reach more people in the first month."),
    (5, "42:08", "Per-order costs fell when we stopped using custom boxes."),
)
QUERIES = (
    ("quote", "raised prices"),
    ("paraphrase", "why the subscription got more expensive"),
)
DEPTH = 3


def encode(model_dir, texts):
    tokenizer = Tokenizer.from_file(str(model_dir / "tokenizer.json"))
    tokenizer.enable_truncation(max_length=256)
    tokenizer.enable_padding()
    batch = tokenizer.encode_batch(texts)
    ids = np.array([row.ids for row in batch], dtype=np.int64)
    mask = np.array([row.attention_mask for row in batch], dtype=np.int64)
    session = ort.InferenceSession(
        str(model_dir / "onnx/model_quantized.onnx"),
        providers=["CPUExecutionProvider"],
    )
    (hidden,) = session.run(
        None, {"input_ids": ids, "attention_mask": mask, "token_type_ids": np.zeros_like(ids)}
    )
    weights = mask[..., None].astype(np.float32)
    pooled = (hidden * weights).sum(axis=1) / weights.sum(axis=1)
    return pooled / np.maximum(np.linalg.norm(pooled, axis=1, keepdims=True), 1e-12)


def literal_query(text):
    return '"' + text.replace('"', '""') + '"'


def fuse(*rankings, k=60):
    scores = defaultdict(float)
    for ranking in rankings:
        for rank, passage_id in enumerate(ranking, start=1):
            scores[passage_id] += 1 / (k + rank)
    return sorted(scores, key=lambda passage_id: (-scores[passage_id], passage_id))


def run(model_dir):
    embeddings = encode(
        model_dir,
        [f"passage: {text}" for _, _, text in PASSAGES]
        + [f"query: {query}" for _, query in QUERIES],
    )
    db = sqlite3.connect(":memory:")
    try:
        db.execute("CREATE VIRTUAL TABLE passage_fts USING fts5(text)")
        db.executemany(
            "INSERT INTO passage_fts(rowid, text) VALUES (?, ?)",
            [(passage_id, text) for passage_id, _, text in PASSAGES],
        )
        examples = []
        for i, (key, query) in enumerate(QUERIES):
            lexical = [
                row[0]
                for row in db.execute(
                    """SELECT rowid FROM passage_fts WHERE passage_fts MATCH ?
                    ORDER BY bm25(passage_fts), rowid LIMIT ?""",
                    (literal_query(query), DEPTH),
                )
            ]
            cosine = embeddings[: len(PASSAGES)] @ embeddings[len(PASSAGES) + i]
            semantic = [
                PASSAGES[index][0]
                for index in sorted(range(len(PASSAGES)), key=lambda index: (-cosine[index], index))[:DEPTH]
            ]
            examples.append({
                "key": key,
                "query": query,
                "lexical": lexical,
                "semantic": semantic,
                "fused": fuse(lexical, semantic)[:DEPTH],
            })
    finally:
        db.close()
    return {
        "passages": [
            {"id": passage_id, "time": time, "text": text}
            for passage_id, time, text in PASSAGES
        ],
        "examples": examples,
    }


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("model_dir", type=Path)
    print(json.dumps(run(parser.parse_args().model_dir), indent=2))
