"""Build-time proof that the baked Hermes runs the hosted web and browser policy.

Both runtime images run this after the Hermes bridge is installed:

    python hermes-web-runtime-check.py '<HERMES_SELLABLE_WEB_POLICY as JSON>' <browser-harness version> <chromium revision>

It never touches the network: the DuckDuckGo worker and the keyless vendors are
replaced by recorders, and everything between them is Hermes's own code. It proves:

* web_search resolves to ddgs and web_extract to Exa's free keyless tier;
* a DuckDuckGo success is never rescued;
* a DuckDuckGo miss ("No results found") or error is rescued exactly once,
  through the keyless tier starting at Exa, and the answer says so;
* web_extract on the keyless tier is never rescued a second time;
* Hermes browser_exec resolves to its baked browser-harness module and baked
  Chromium at the pinned revision without any runtime download.

Any mismatch exits non-zero and fails the image build.
"""

import importlib.metadata
import json
import os
import sys
import tempfile
import types

POLICY = json.loads(sys.argv[1])
BROWSER_HARNESS_VERSION = sys.argv[2]
CHROMIUM_BROWSER_REVISION = sys.argv[3]


def fail(message):
    sys.stderr.write(f"hermes_web_runtime_check_failed: {message}\n")
    sys.exit(1)


home = tempfile.mkdtemp(prefix="hermes-web-check-")
with open(os.path.join(home, "config.yaml"), "w", encoding="utf-8") as handle:
    json.dump({"web": POLICY}, handle)
os.environ["HERMES_HOME"] = home
os.environ["HOME"] = home
sys.path.insert(0, "/opt/hermes")
os.chdir("/opt/hermes")

from tools import web_tools  # noqa: E402
from tools.web_tools_rescue import _rescue_eligible  # noqa: E402
import plugins.web.ddgs.provider as ddgs_provider  # noqa: E402
import plugins.web.keyless_mcp as keyless  # noqa: E402

if web_tools._get_search_backend() != "ddgs":
    fail(f"search backend is {web_tools._get_search_backend()!r}, not ddgs")
if web_tools._get_extract_backend() != "exa":
    fail(f"extract backend is {web_tools._get_extract_backend()!r}, not exa")
if not keyless.use_keyless("exa", ""):
    fail("exa does not run on its free keyless tier")

tiers = POLICY.get("provider_tier") or {}
expected_ring = [v for v in keyless._KEYLESS_RING if tiers.get(v) != "paid"]
ring = keyless._ring_order("ddgs")
if not ring or ring[0] != "exa" or ring != expected_ring:
    fail(f"a ddgs rescue would walk {ring}, expected {expected_ring} starting at exa")

rescues = []
vendor_calls = []
real_search_with_failover = keyless.search_with_failover


def counted_search_with_failover(name, query, limit=5):
    rescues.append(name)
    return real_search_with_failover(name, query, limit)


keyless.search_with_failover = counted_search_with_failover
for vendor in keyless._KEYLESS_RING:
    keyless._KEYLESS_SEARCHERS[vendor] = (
        lambda query, limit, _vendor=vendor: vendor_calls.append(_vendor)
        or {"success": True, "data": {"web": [
            {"title": _vendor, "url": f"https://{_vendor}.example/", "description": "", "position": 1}
        ]}}
    )

ddgs_provider._run_ddgs_search_bounded = lambda query, limit: [
    {"title": "ddgs", "url": "https://ddgs.example/", "description": "", "position": 1}
]
ok = json.loads(web_tools.web_search_tool("hermes web check hit", limit=3))
if not ok.get("success") or rescues or vendor_calls or (ok.get("data") or {}).get("rescued_from"):
    fail(f"a DuckDuckGo success was rescued: {ok} {rescues} {vendor_calls}")


def no_results(query, limit):
    raise RuntimeError("No results found.")


def broken(query, limit):
    raise TimeoutError("ddgs worker timed out")


for label, ddgs_failure in (("miss", no_results), ("error", broken)):
    rescues.clear()
    vendor_calls.clear()
    ddgs_provider._run_ddgs_search_bounded = ddgs_failure
    rescued = json.loads(web_tools.web_search_tool(f"hermes web check {label}", limit=3))
    data = rescued.get("data") or {}
    if rescues != ["ddgs"] or vendor_calls != ["exa"]:
        fail(f"a DuckDuckGo {label} made rescues {rescues} through {vendor_calls}, expected one through exa")
    if not rescued.get("success") or data.get("rescued_from") != "ddgs":
        fail(f"the rescued {label} search did not report its rescue: {rescued}")

if _rescue_eligible(types.SimpleNamespace(name="exa")):
    fail("a keyless Exa extract failure would be rescued a second time")

from tools.browser_launcher import _resolve_executable, chromium_ready  # noqa: E402
from tools.browser_use_cli import _find_cli, browser_exec_available  # noqa: E402

if not browser_exec_available():
    fail("Hermes browser_exec is unavailable")
cli = _find_cli()
expected_cli = [sys.executable, "-m", "browser_harness.run"]
if cli != expected_cli:
    fail(f"Hermes resolves browser_exec CLI to {cli!r}, expected {expected_cli!r}")
installed_harness = importlib.metadata.version("browser-harness")
if installed_harness != BROWSER_HARNESS_VERSION:
    fail(f"browser-harness version is {installed_harness!r}, expected {BROWSER_HARNESS_VERSION!r}")

ready, hint = chromium_ready()
executable = _resolve_executable()
expected_prefix = f"/opt/hermes/tools/chromium-{CHROMIUM_BROWSER_REVISION}/"
if not ready or not executable or not executable.startswith(expected_prefix) or not os.access(executable, os.X_OK):
    fail(f"baked Chromium rev {CHROMIUM_BROWSER_REVISION} not ready: ready={ready!r} exe={executable!r} hint={hint!r}")

print(
    f"hermes web runtime check: search ddgs, extract exa free, one rescue via {ring} on a ddgs miss, "
    f"browser-harness {BROWSER_HARNESS_VERSION} + chromium-{CHROMIUM_BROWSER_REVISION} at {executable}"
)
