"""Unfiltered vs section-filtered search, then filter variants with hit counts."""
from qdrant_client import QdrantClient, models
from common import COLLECTION, embed_query, read_chunks

client = QdrantClient(url="http://localhost:6333")
_, model, _ = read_chunks()
Q = "How do I get notified when a crawl job finishes?"
vec = embed_query(Q, model)


def show(title, flt=None, limit=5):
    res = client.query_points(COLLECTION, query=vec, query_filter=flt, limit=limit, with_payload=True)
    print(f"\n== {title}")
    for p in res.points:
        pl = p.payload
        print(f"{p.score:.3f}  [{pl['section']}]  {pl['heading'] or '(no heading)'}  {pl['url'].replace('https://webcrawlerapi.com','')}")
    return res.points


def f(**kw):
    return models.Filter(**kw)


def sec(v):
    return models.FieldCondition(key="section", match=models.MatchValue(value=v))


print("Question:", Q)
show("no filter")
pts = show("section = sdk", f(must=[sec("sdk")]))
assert all(p.payload["section"] == "sdk" for p in pts)
pts = show("section = guides", f(must=[sec("guides")]))
assert all(p.payload["section"] == "guides" for p in pts)

print("\n== filter variants (count, exact)")
variants = {
    "must section=api": f(must=[sec("api")]),
    "must section=sdk": f(must=[sec("sdk")]),
    "must MatchAny section in [guides, errors]": f(must=[models.FieldCondition(key="section", match=models.MatchAny(any=["guides", "errors"]))]),
    "should section=api OR section=sdk": f(should=[sec("api"), sec("sdk")]),
    "must_not section=api": f(must_not=[sec("api")]),
    "must section=api AND must_not url=/docs/api/crawl": f(
        must=[sec("api")],
        must_not=[models.FieldCondition(key="url", match=models.MatchValue(value="https://webcrawlerapi.com/docs/api/crawl"))],
    ),
}
print(f"total: {client.count(COLLECTION, exact=True).count}")
for name, flt in variants.items():
    print(f"{client.count(COLLECTION, count_filter=flt, exact=True).count:4d}  {name}")
