"""Pins the toy in embed_search.py to what the lesson says about it."""
# guards: new lesson tool; the lesson's claims (words miss a paraphrase, meaning finds it, a cosine ignores length, an unknown word has no
# vector, one cell can miss) each rest on numbers the toy prints, and a toy edit must not leave the lesson saying something the code no longer does
import math
import re
import subprocess
import sys
from pathlib import Path

import pytest

import embed_search as es
import make_figs

VECTORS = [es.embed(d) for d in es.DOCS]
CODE = Path(__file__).resolve().parent
LESSON = (CODE.parent / "lesson.md").read_text(encoding="utf-8")
SOURCE = (CODE / "embed_search.py").read_text(encoding="utf-8")


def run(script, *args, cwd=CODE):
    return subprocess.run([sys.executable, str(script), *args], cwd=cwd, capture_output=True, text=True, check=True).stdout


def part(start, end):
    """The lesson text from one heading up to the next."""
    return LESSON.split(start, 1)[1].split(end, 1)[0]


def fences(text):
    return re.findall(r"```(\w+)\n(.*?)```", text, re.S)


# guards: a toy edit that changes which sentence each way of searching puts first, which the lesson's table of six questions quotes
@pytest.mark.parametrize("question, words_best, words_score, meaning_best, meaning_score", [
    ("Can I get my money back?", 3, 2, 0, 1.0),                       # words pick the login page (get, back); meaning picks the repay sentence
    ("I lost my password", 2, 1, 3, 0.998),
    ("When are you open?", 5, 1, 6, 1.0),                              # "open" does not match "Opening": no stemming
    ("Where is my order?", 0, 0, 4, 0.976),                            # no shared word at all: every sentence scores 0, list order wins
    ("Code E4410", 8, 1, 0, 0.0),                                      # no word the toy knows: every cosine is 0, list order wins
    ("Can I pay for delivery?", 7, 2, 7, 0.962),
])
def test_each_question_gets_the_words_best_and_the_meaning_best_the_lesson_names(question, words_best, words_score, meaning_best, meaning_score):
    assert es.rank_keywords(question)[0] == (words_best, words_score)
    index, score = es.rank_meaning(question)[0]
    assert index == meaning_best and score == pytest.approx(meaning_score, abs=5e-4)


# guards: someone swapping cosine for a plain dot product, which grows with the length of the lists and ranks a long list first; also the
# lesson's two side claims, that for length-1 lists the squared distance is 2 - 2 x cosine, and that embed is a sum so word order is ignored
def test_cosine_ignores_length_where_dot_does_not():
    short, long, other = (1.0, 0.0, 0.0, 0.0), (5.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0)
    assert es.dot(short, long) == 5.0 and es.cosine(short, long) == 1.0 and es.cosine(short, other) == 0.0
    assert es.cosine((0.0, 0.0, 0.0, 0.0), short) == 0.0                                       # an empty list divides by zero without the guard
    assert all(es.length(v) == pytest.approx(1.0) for v in VECTORS if any(v))                  # embed scales a known sentence to length 1
    assert math.dist(VECTORS[1], VECTORS[7]) ** 2 == pytest.approx(2 - 2 * es.cosine(VECTORS[1], VECTORS[7]))
    assert es.embed("refund card") == es.embed("card refund")


# guards: an unknown identifier: the toy has no numbers for it, so meaning search cannot rank anything while words still find the sentence
def test_a_question_with_no_known_word_has_a_zero_list_and_only_words_find_it():
    assert es.embed("Code E4410") == (0.0, 0.0, 0.0, 0.0)
    assert {score for _, score in es.rank_meaning("Code E4410")} == {0.0}
    assert es.shared_words("Code E4410", es.DOCS[8]) == ["e4410"]


# guards: the approximate-search claim: one cell is cheaper and can miss the best sentence, two cells find it again
def test_closest_cell_only_misses_what_two_cells_find():
    question = es.embed("Can I pay for delivery?")
    exact = es.nearest(question, VECTORS, 1)[0][0]
    assert exact == 7 and es.cell_search(question, VECTORS, 1) == (4, 1) and es.cell_search(question, VECTORS, 2) == (7, 5)
    assert es.cell_search(question, VECTORS, len(es.TOPICS)) == (exact, len(es.DOCS))           # every cell is the full scan
    assert es.scan_cost(1_000_000, 768) == 768_000_000


# guards: the lesson's "A real run" block drifting from what show_numbers.py prints, and its line cites drifting from embed_search.py after an edit
def test_the_real_run_block_and_the_line_cites_match_the_code():
    blocks = fences(part("### A real run", "\n## Your turn"))
    assert blocks[0] == ("bash", "cd code && uv run --no-project python show_numbers.py\n")
    assert blocks[1] == ("text", run("show_numbers.py"))
    lines = SOURCE.splitlines()
    cites = re.findall(r"`embed_search\.py:(\d+)`<br>`([^`]+)`", LESSON)
    assert len(cites) == 5 and all(lines[int(n) - 1].strip() == text for n, text in cites)
    in_prose = {100: "if length(a) == 0", 101: "return 0.0", 109: ".get(w, ())", 110: "total[i] += x", 111: "size = length(total)",
                117: "scored = [", 135: "def cell_of", 137: "return max(", 146: "return [i for c in order", 149: "def cell_search"}
    assert all(text in lines[n - 1] for n, text in in_prose.items())


# guards: a code block in "Go deeper" that no longer appears in embed_search.py, so a reader copies code the lesson never ran
def test_every_python_block_in_the_lesson_is_verbatim_in_the_code():
    blocks = [body.rstrip("\n") for lang, body in fences(LESSON) if lang == "python"]
    assert len(blocks) == 5 and all(block in SOURCE for block in blocks)


# guards: the "Your turn" step: the line to add, and the before and after output, must be what the toy prints (the edit is made on a copy)
def test_your_turn_edit_gives_the_output_the_lesson_shows(tmp_path):
    turn = part("## Your turn", "## What this means")
    line = re.search(r'add the line `("cash": \([^`]+\),)` inside', turn).group(1)
    question = re.search(r'embed_search\.py "([^"]+)"', turn).group(1)
    anchor = '    "money": (1.0, 0.0, 0.0, 0.0),\n'
    assert anchor in SOURCE
    (tmp_path / "embed_search.py").write_text(SOURCE.replace(anchor, anchor + "    " + line + "\n"), encoding="utf-8")
    before, after = [body for lang, body in fences(turn) if lang == "text"]
    assert before == run(CODE / "embed_search.py", question)
    assert after == run(tmp_path / "embed_search.py", question, cwd=tmp_path)


# guards: a figure that no longer matches what make_figs.py draws, or alt text that states a number the figure does not show
def test_figures_are_what_the_code_draws_and_their_alt_numbers_are_in_them():
    for name, draw in make_figs.FILES.items():
        assert (make_figs.FIGS / name).read_text(encoding="utf-8") == draw()
    shown = re.findall(r"!\[([^\]]*)\]\(figs/([^)]+)\)", LESSON)
    assert sorted(name for _, name in shown) == sorted(make_figs.FILES)
    for alt, name in shown:
        svg = (make_figs.FIGS / name).read_text(encoding="utf-8")
        assert all(number in svg for number in re.findall(r"\d+\.\d+", alt))
