"""Folate 0.1.1: synthetic HTML only. No browser or real website is operated."""
import json
from pathlib import Path
import onnxruntime as ort
from huggingface_hub import hf_hub_download
from folate import FolateSelectorFinder

REVISION = "d1ffc1d47fc8a69a1b072b83de05b2fbb1477196"
ort.disable_telemetry_events()
files = [hf_hub_download("figranium/folate", name, revision=REVISION)
         for name in ("model_quantized.onnx", "tokenizer.json")]
finder = FolateSelectorFinder(model_dir=str(Path(files[0]).parent), num_threads=4)
query = "航空券を検索するボタンを押す"
small_en = '<button id="b1">Search Flights</button><button id="b2">Cancel</button><button id="b3">Delete Account</button>'
small_ja = '<button id="b1">航空券を検索</button><button id="b2">キャンセル</button><button id="b3">アカウント削除</button>'
many = ''.join(f'<button id="b{i}">項目{i}</button>' for i in range(1, 49))
many += '<button id="target">航空券を検索</button>'
cases = [
    ("English / 3", "click Search Flights button", small_en, 48, "#b1"),
    ("Japanese / 3", query, small_ja, 48, "#b1"),
    ("Japanese / 49, default cap", query, many, 48, "#target"),
    ("Japanese / 49, expanded cap", query, many, 49, "#target"),
    ("No controls", query, "<p>No controls</p>", 48, None),
]
for label, instruction, html, limit, expected in cases:
    matches = finder.rank(instruction, html, max_candidates=limit, top_k=3)
    top = matches[0]["selector"] if matches else None
    print(json.dumps({"case": label, "expected": expected, "top": top,
                      "matched": top == expected, "matches": matches}, ensure_ascii=False))
# Internal preprocessing audit, tied to package 0.1.1 (not a stable public API).
candidates = finder.extract_candidates(many)
assert len(candidates) == 49
assert not any(c["selector"] == "#target" for c in finder._prefilter_candidates(query, candidates, 48))
assert any(c["selector"] == "#target" for c in finder._prefilter_candidates(query, candidates, 49))
assert finder.rank(query, "<p>No controls</p>") == []
duplicates = finder.extract_candidates('<button name="action">閲覧</button><button name="action">削除</button>')
assert len(duplicates) == 2 and duplicates[0]["selector"] == duplicates[1]["selector"]
print("Structural checks passed. Ranking output is an observation, not a general accuracy score.")
