"""Small, inspectable retrieval lab. Python 3.10+, standard library only.

Save in your exercise folder; run python week07.py --lesson 1 (or 2, 3, all).
Core mode uses a HANDCRAFTED feature encoder, not a trained semantic model.
Optional: --embedding-url http://localhost:11434/api/embed --model YOUR_MODEL
uses an already installed local Ollama embedding model. This is a real separate
inference run; no model download is performed and fixture results do not verify
its quality. The core path needs no network or credentials.
"""
import argparse
import json
import math
import re
import urllib.parse
import urllib.request

DOCS = [
    {"id": "access", "text": "Staff reset a forgotten password online.", "scope": "public", "code": ""},
    {"id": "contract", "text": "Contractors with lost credentials contact support.", "scope": "public", "code": ""},
    {"id": "zx41", "text": "ZX-41 reset: hold the button for five seconds.", "scope": "public", "code": "ZX-41"},
    {"id": "zx14", "text": "ZX-14 reset: hold the button for ten seconds.", "scope": "public", "code": "ZX-14"},
    {"id": "billing", "text": "An overdue invoice requires payment.", "scope": "public", "code": ""},
    {"id": "secret", "text": "North lost credentials; private recovery code 9988.", "scope": "private", "code": ""},
]
GROUPS = [set("password forgotten forgot credentials lost access sign reset".split()),
          set("invoice overdue payment billing".split()), set("support contractors".split())]


def validate_local_url(url):
    parsed = urllib.parse.urlsplit(url)
    if (parsed.scheme != "http" or parsed.hostname not in {"localhost", "127.0.0.1", "::1"}
            or parsed.username is not None or parsed.password is not None
            or parsed.port is None or not 1 <= parsed.port <= 65535 or parsed.fragment):
        raise ValueError("use an explicit loopback HTTP endpoint without user information or fragments")
    return url


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        raise ValueError("optional local endpoint redirects are not allowed")


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


def embed(text):
    words = tokens(text)
    return [sum(word in group for word in words) for group in GROUPS]


def cosine(a, b):
    if len(a) != len(b):
        raise ValueError("incompatible dimensions")
    norm = math.sqrt(sum(x*x for x in a) * sum(y*y for y in b))
    return sum(x*y for x, y in zip(a, b)) / norm if norm else 0.0


def eligible(scope="public"):
    return [dict(d) for d in DOCS if d["scope"] == "public" or scope == "private"]


def rankings(query, docs, encoder=embed):
    query_words = set(tokens(query))
    query_vector = encoder(query)
    lexical = sorted(docs, key=lambda d: (-len(query_words & set(tokens(d["text"]))), d["id"]))
    dense = sorted(docs, key=lambda d: (-cosine(query_vector, encoder(d["text"])), d["id"]))
    scores = {}
    for ranking in (lexical[:4], dense[:4]):
        for rank, doc in enumerate(ranking, 1):
            scores[doc["id"]] = scores.get(doc["id"], 0) + 1 / (10 + rank)
    fused = sorted([d for d in docs if d["id"] in scores], key=lambda d: (-scores[d["id"]], d["id"]))
    # Transparent rule reranker: exact code first; then fused order unchanged.
    codes = {word.upper() for word in tokens(query) if "-" in word}
    reranked = sorted(fused, key=lambda d: d["code"] not in codes)
    return lexical, dense, fused, reranked


def lesson1():
    assert validate_local_url("http://127.0.0.1:11434/api/embed")
    for url in ("http://127.0.0.1:11434@example.org/api/embed", "http://localhost:1234@elsewhere.invalid/", "http://example.org:1234/", "http://user@localhost:1234/"):
        try:
            validate_local_url(url)
            raise AssertionError("nonlocal or userinfo endpoint accepted")
        except ValueError:
            pass
    try:
        NoRedirect().redirect_request(None, None, 302, "Found", {}, "http://elsewhere.invalid/")
        raise AssertionError("redirect accepted")
    except ValueError:
        pass
    assert cosine([1, 0], [0, 1]) == 0
    assert cosine([0, 0], [1, 0]) == 0
    assert math.isclose(cosine([3, 4], [4, 3]), 0.96)
    try:
        cosine([1, 0], [1])
        raise AssertionError("dimension mismatch accepted")
    except ValueError:
        pass
    source = "Employees reset passwords online. Contractors contact support."
    start, end = 0, source.index(".") + 1
    chunk = {"source": "policy-v1", "start": start, "end": end, "text": source[start:end]}
    assert source[chunk["start"]:chunk["end"]] == chunk["text"]
    assert embed("ZX-41 reset") == embed("ZX-14 reset")  # deliberate limitation
    for query in ("forgot password", "ZX-41 reset"):
        print("dense", query, [d["id"] for d in rankings(query, eligible())[1]])
    print("PASS lesson 1: cosine, zero, compatibility, offsets; exact-code collision recorded")


def lesson2():
    public = eligible()
    assert all(d["id"] != "secret" for d in public)
    for query in ("lost credentials", "ZX-41 reset"):
        results = rankings(query, public)
        for label, ranking in zip(("lexical", "dense", "fused", "reranked"), results):
            assert "secret" not in [d["id"] for d in ranking]
            print(label, query, [d["id"] for d in ranking])
        if query == "ZX-41 reset":
            assert results[3][0]["id"] == "zx41"
    print("PASS lesson 2: filtered candidates never contain private text; exact-code reranker checked")


def supported_quote(claim, source_id, context):
    return any(d["id"] == source_id and claim in d["text"] for d in context)


def lesson3():
    assert len({"A", "C"} & {"A", "B", "D"}) / 2 == 0.5
    public = eligible()
    cases = [("forgot password", {"access"}), ("ZX-41 reset", {"zx41"}), ("backup retention", set())]
    recalls = []
    for query, relevant in cases:
        retrieved = rankings(query, public)[3][:2]
        if relevant:
            recall = len(relevant & {d["id"] for d in retrieved}) / len(relevant)
            recalls.append(recall)
            print("query", query, "recall@2", recall)
        else:
            answer = {"status": "abstain", "reason": "No labeled support in this corpus"}
            assert answer["status"] == "abstain"
            print("query", query, "appropriate fixture abstention")
    assert supported_quote("Staff reset", "access", public)
    assert not supported_quote("Staff reset", "invented", public)
    assert not supported_quote("within two days", "access", public)
    print("mean answerable recall@2", sum(recalls) / len(recalls))
    print("PASS lesson 3: metric arithmetic, citation identity, exact support, and abstention fixture")


def optional_embedding_run(url, model):
    validate_local_url(url)
    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
    def encode(text):
        body = json.dumps({"model": model, "input": text}).encode()
        request = urllib.request.Request(url, body, {"Content-Type": "application/json"})
        with opener.open(request, timeout=30) as response:
            vector = json.load(response)["embeddings"][0]
        if not vector or not all(type(x) in (int, float) and math.isfinite(x) for x in vector):
            raise ValueError("invalid embedding result")
        return vector
    ranking = rankings("forgot password", eligible(), encode)[1]
    print("REAL optional local-model ranking:", [d["id"] for d in ranking])
    print("Inspect against fixed labels; endpoint execution alone is not a model-quality pass.")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--lesson", choices=["1", "2", "3", "all"], default="all")
    parser.add_argument("--embedding-url")
    parser.add_argument("--model", default="")
    args = parser.parse_args()
    for number, function in enumerate((lesson1, lesson2, lesson3), 1):
        if args.lesson in (str(number), "all"):
            function()
    if args.embedding_url:
        if not args.model:
            parser.error("--model is required for an optional embedding endpoint")
        optional_embedding_run(args.embedding_url, args.model)


if __name__ == "__main__":
    main()
