"""Hash-pinned CPU checks of source JSON handling only with no model inference."""

import contextlib
import hashlib
import importlib.util
import io
import json
import sys
import tempfile
import urllib.request
from pathlib import Path

REVISION = "1abb2b26c9af833cae34c66bdde95865f73dc117"
SHA256 = "29747f7746ccffd83f3490050da5394b38062b9eeb9ecd43633cad23f45cc847"
URL = f"https://raw.githubusercontent.com/zhangzhuoran997997/Verus-Insight/{REVISION}/src/verus_insight/common.py"
source = (
    Path(sys.argv[1]).read_bytes()
    if len(sys.argv) > 1
    else urllib.request.urlopen(URL, timeout=30).read()
)
assert hashlib.sha256(source).hexdigest() == SHA256
with tempfile.TemporaryDirectory(prefix="clout-verus-json-") as temp:
    module_path = Path(temp) / "source.py"
    module_path.write_bytes(source)
    spec = importlib.util.spec_from_file_location("verus_saved_source", module_path)
    assert spec is not None and spec.loader is not None
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    cases = [
        ("empty object", "{}", True),
        (
            "nested unknown verdict",
            '{"stage_targets":{"audit":{"verdict":"unknown-example"}}}',
            True,
        ),
        ("nested out of bounds field", '{"bbox":[-1,0,1001,20]}', True),
        ("array", "[]", False),
        ("nonfinite constant", '{"x":NaN}', False),
        ("trailing text", "{} trailing", False),
    ]
    checked = []
    for name, text, passes in cases:
        r = mod.make_result(text, "stop", model="Authored CPU fixture")
        assert (r["parse_error"] is None) == passes
        checked.append({"case": name, "sourceObjectParsePasses": passes})
    incomplete = mod.make_result("{}", "length")
    assert incomplete["parse_error"] is None and incomplete["finish_reason"] == "length"
    saved = Path(temp) / "incomplete.json"
    try:
        with contextlib.redirect_stdout(io.StringIO()):
            mod.write_result(saved, incomplete)
    except RuntimeError:
        pass
    else:
        raise AssertionError("Incomplete response did not fail after saving")
    assert json.loads(saved.read_text())["finish_reason"] == "length"
    print(
        json.dumps(
            {
                "revision": REVISION,
                "sourceSHA256": SHA256,
                "cases": checked,
                "incompleteJSONCanParse": True,
                "incompleteWriteSavesThenRaises": True,
                "scope": "Selected source JSON and completion handling only no weights GPU or generated media",
            },
            indent=2,
        )
    )
