"""Synthetic vector retrieval: no model, external service or third-party dependencies.
Run with --self-test. The CLI tenant is trusted configuration for this demo only.
A web service must derive scope from authenticated identity, not client input.
"""
import argparse
import math
import json
from dataclasses import dataclass

@dataclass(frozen=True)
class Record:
    id: str
    source: str
    tenant: str
    current: bool
    vector: tuple

RECORDS = (
    Record("N-1", "synthetic://current-maintenance", "north", True, (.92, .39)),
    Record("S-1", "synthetic://other-division", "south", True, (1., 0.)),
    Record("N-0", "synthetic://expired-maintenance", "north", False, (.99, .1)),
    Record("N-2", "synthetic://travel", "north", True, (.1, .99)),
)

def cosine(a, b):
    if not a or len(a) != len(b) or not all(math.isfinite(x) for x in (*a, *b)):
        raise ValueError("Vectors must have equal nonzero dimensions and finite values")
    na, nb = math.hypot(*a), math.hypot(*b)
    if not na or not nb:
        raise ValueError("Zero vectors have no cosine direction")
    return sum(x*y for x, y in zip(a, b))/(na*nb)

def retrieve(query, tenant, records=RECORDS, current_only=True, limit=3):
    if not tenant or not isinstance(limit, int) or limit < 1:
        raise ValueError("Trusted tenant scope and positive limit required")
    cosine(query, query)  # validate even when no candidates are eligible
    eligible = (r for r in records if r.tenant == tenant and (r.current or not current_only))
    result = [{"id": r.id, "source": r.source, "score": cosine(query, r.vector)} for r in eligible]
    return sorted(result, key=lambda r: (-r["score"], r["id"]))[:limit]

def self_test():
    assert [r["id"] for r in retrieve((1,0), "north")] == ["N-1", "N-2"]
    assert retrieve((1,0), "south")[0]["id"] == "S-1"
    assert retrieve((1,0), "north", current_only=False)[0]["id"] == "N-0"
    assert retrieve((0,1), "north")[0]["id"] == "N-2"
    assert retrieve((1,0), "absent") == []
    for a,b in [((0,0),(1,0)), ((1,),(1,0)), ((float("nan"),0),(1,0))]:
        try: cosine(a,b)
        except ValueError: pass
        else: raise AssertionError("Invalid vector accepted")
    print("PASS: scope, freshness, ranking, empty scope, zero, dimensions, finite values")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--self-test", action="store_true")
    parser.add_argument("--tenant", choices=("north", "south"), default="north")
    parser.add_argument("--query", nargs=2, type=float, default=[1.,0.])
    args = parser.parse_args()
    if args.self_test: self_test()
    else: print(json.dumps(retrieve(tuple(args.query), args.tenant), indent=2))
