"""Embed the retrieval round's chunks and questions with an open embedding model run locally on CPU, and write
evals/retrieval-embeddings.json. Replay and scoring read the stored vectors and never need this script or the model.

    python3 -B embed_retrieval.py --model-dir <folder for the model files>          # write the vectors
    python3 -B embed_retrieval.py --model-dir <folder> --check                       # recompute and compare rankings

Needs the packages in requirements-embeddings.lock. The model is BAAI/bge-small-en-v1.5 (MIT licence), in the quantized
ONNX build the fastembed library downloads; chunks are embedded as passages and questions as queries (the model's query
instruction). Vectors are rounded to 6 decimals before they are stored and ranked.
"""
from pathlib import Path
import argparse
import hashlib
import json
import os
import sys

for var in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS'):
    os.environ.setdefault(var, '1')

ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))
from banking import retrieval as R  # noqa: E402


MODEL_FILES = ('model_optimized.onnx', 'tokenizer.json', 'tokenizer_config.json', 'special_tokens_map.json', 'config.json')


def model_files(model_dir):
    """sha256 of the model's weights and tokenizer files, from the downloaded snapshot."""
    out = {}
    for p in sorted(Path(model_dir).rglob('*')):
        if p.name in MODEL_FILES and 'snapshots' in p.parts:
            out[p.name] = hashlib.sha256(p.resolve().read_bytes()).hexdigest()
    if set(out) != set(MODEL_FILES):
        raise SystemExit('Model files missing from the snapshot')
    return dict(sorted(out.items()))


def compute(model_dir):
    import fastembed
    from fastembed import TextEmbedding
    model = TextEmbedding(R.EMBEDDING_MODEL, cache_dir=str(model_dir), threads=1)
    chunks = R.chunks()
    questions = R.read(R.QUESTIONS)['questions'] + R.read(R.DEVELOPMENT)['questions']
    cv = list(model.passage_embed([c['text'] for c in chunks]))
    qv = list(model.query_embed([q['text'] for q in questions]))
    rnd = lambda v: [round(float(x), 6) for x in v]  # noqa: E731
    return {
        'note': 'Vectors of the retrieval round, stored so that ranking and replay need no embedding model. Chunks are embedded as passages, questions as queries.',
        'model': R.EMBEDDING_MODEL, 'library': f'fastembed {fastembed.__version__}', 'dimensions': R.DIMENSIONS,
        'model_files_sha256': model_files(model_dir),
        'chunks': [{'id': c['id'], 'text_sha256': R.sha_text(c['text']), 'vector': rnd(v)} for c, v in zip(chunks, cv)],
        'questions': {q['id']: rnd(v) for q, v in zip(questions, qv)},
    }


def rankings(store):
    return {qid: [h['id'] for h in R.vector_ranking(qid, store=store)] for qid in store['questions']}


def main():
    p = argparse.ArgumentParser()
    p.add_argument('--model-dir', required=True)
    p.add_argument('--check', action='store_true')
    a = p.parse_args()
    fresh = compute(a.model_dir)
    if a.check:
        stored = R.embeddings()
        same = rankings(fresh) == rankings(stored) and fresh['model_files_sha256'] == stored['model_files_sha256']
        print(f'VERDICT: {"PASS" if same else "FAIL"} (recomputed vectors give the stored top-{R.TOP_K} rankings for every question)')
        sys.exit(0 if same else 1)
    out = ROOT / R.EMBEDDINGS
    if out.exists():
        raise SystemExit('evals/retrieval-embeddings.json exists and is frozen; use --check')
    out.write_text(json.dumps(fresh, ensure_ascii=False) + '\n', encoding='utf-8')
    print(f'VERDICT: PASS (wrote {len(fresh["chunks"])} chunk and {len(fresh["questions"])} question vectors)')


if __name__ == '__main__':
    main()
