"""A toy that finds text that means the same thing. Standard library only.

Every number about a word is picked by hand for the lesson. A real embedding model learns
many more numbers per text from lots of writing; the steps after that are the ones here.
"""
import math
import re
import sys

TOPICS = ("money", "account", "delivery", "hours")

# What each word is about, one number per topic. A word that is not here carries no topic.
WORD_VECTORS = {
    "repay": (1.0, 0.0, 0.0, 0.0),
    "refund": (1.0, 0.0, 0.0, 0.0),
    "money": (1.0, 0.0, 0.0, 0.0),
    "paid": (0.9, 0.0, 0.0, 0.0),
    "pay": (0.9, 0.0, 0.0, 0.0),
    "payment": (1.0, 0.0, 0.0, 0.0),
    "card": (0.8, 0.1, 0.0, 0.0),
    "extra": (0.3, 0.0, 0.0, 0.0),
    "failed": (0.4, 0.2, 0.0, 0.0),
    "error": (0.2, 0.2, 0.0, 0.0),
    "password": (0.0, 1.0, 0.0, 0.0),
    "login": (0.0, 1.0, 0.0, 0.0),
    "forgot": (0.0, 0.5, 0.0, 0.0),
    "lost": (0.1, 0.4, 0.0, 0.0),
    "sign": (0.0, 0.6, 0.0, 0.0),
    "page": (0.1, 0.2, 0.1, 0.0),
    "parcel": (0.0, 0.0, 1.0, 0.0),
    "ships": (0.0, 0.0, 0.9, 0.0),
    "delivery": (0.0, 0.0, 1.0, 0.0),
    "order": (0.2, 0.0, 0.9, 0.0),
    "fast": (0.0, 0.0, 0.3, 0.2),
    "open": (0.0, 0.0, 0.0, 1.0),
    "opening": (0.0, 0.0, 0.0, 1.0),
    "times": (0.0, 0.0, 0.0, 0.6),
    "weekdays": (0.0, 0.0, 0.0, 0.7),
    "shop": (0.2, 0.0, 0.1, 0.3),
}

# Short filler words that keyword search skips.
STOP_WORDS = {"a", "an", "and", "are", "can", "do", "for", "from", "how", "i", "in", "is", "it", "means",
              "my", "of", "on", "the", "to", "we", "when", "where", "with", "you", "your"}

DOCS = [
    "Cancel within five days and we repay you in full.",
    "A refund reaches your card in five days.",
    "Forgot your password? We can send a new one.",
    "Get back to the login page and sign in again.",
    "Your parcel ships within two days.",
    "The shop is open from nine to five.",
    "Opening times are nine to five on weekdays.",
    "Pay extra for fast delivery with your card.",
    "Error E4410 means your payment failed.",
]

QUERIES = [
    "Can I get my money back?",
    "I lost my password",
    "When are you open?",
    "Where is my order?",
    "Code E4410",
    "Can I pay for delivery?",
]


def words(text):
    return re.findall(r"[a-z0-9]+", text.lower())


def content_words(text):
    return [w for w in words(text) if w not in STOP_WORDS]


def shared_words(query, doc):
    """The content words that the question and the document have in common, in the question's order."""
    doc_words = set(content_words(doc))
    seen = []
    for w in content_words(query):
        if w in doc_words and w not in seen:
            seen.append(w)
    return seen


def keyword_score(query, doc):
    return len(shared_words(query, doc))


def length(v):
    return math.sqrt(sum(x * x for x in v))


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def cosine(a, b):
    """1 when two lists point the same way, 0 when they share nothing, whatever their lengths."""
    if length(a) == 0 or length(b) == 0:
        return 0.0
    return dot(a, b) / (length(a) * length(b))


def embed(text):
    """Add up the lists of the words the toy knows, then scale the result to length 1."""
    total = [0.0] * len(TOPICS)
    for w in words(text):
        for i, x in enumerate(WORD_VECTORS.get(w, ())):
            total[i] += x
    size = length(total)
    return tuple(x / size for x in total) if size else tuple(total)


def nearest(query_vector, vectors, k):
    """Score every stored vector against the question and keep the k best: (index, cosine), best first."""
    scored = [(i, cosine(query_vector, v)) for i, v in enumerate(vectors)]
    return sorted(scored, key=lambda pair: (-pair[1], pair[0]))[:k]


def rank_keywords(query, docs=DOCS):
    scored = [(i, keyword_score(query, d)) for i, d in enumerate(docs)]
    return sorted(scored, key=lambda pair: (-pair[1], pair[0]))


def rank_meaning(query, docs=DOCS):
    return nearest(embed(query), [embed(d) for d in docs], len(docs))


def scan_cost(n_docs, dims):
    """Multiplications to compare one question with every stored vector of length 1."""
    return n_docs * dims


def cell_of(v):
    """A toy cell: the topic where the list is largest."""
    return max(range(len(v)), key=lambda i: v[i])


def cells_checked(query_vector, vectors, probes):
    """The indexes in the `probes` cells whose topic the question leans on most, cell by cell."""
    cells = {}
    for i, v in enumerate(vectors):
        cells.setdefault(cell_of(v), []).append(i)
    order = sorted(range(len(query_vector)), key=lambda c: (-query_vector[c], c))[:probes]
    return [i for c in order for i in cells.get(c, [])]


def cell_search(query_vector, vectors, probes):
    """Compare the question only with the vectors in those cells. Returns (best index, how many were compared)."""
    scanned = cells_checked(query_vector, vectors, probes)
    best = max(scanned, key=lambda i: (cosine(query_vector, vectors[i]), -i)) if scanned else None
    return best, len(scanned)


def config():
    """Everything ../widget.html needs, so its page script can run the same steps."""
    return {
        "topics": list(TOPICS),
        "docs": DOCS,
        "queries": QUERIES,
        "words": {w: list(v) for w, v in WORD_VECTORS.items()},
        "stop": sorted(STOP_WORDS),
        "opening": {"query": 0, "mode": "words"},
    }


if __name__ == "__main__":
    q = sys.argv[1] if len(sys.argv) > 1 else QUERIES[0]
    print("question:", q)
    for i, score in rank_meaning(q)[:3]:
        print(f"  {score:.3f}  {DOCS[i]}")
