"""Reproduce a public Markdown syntax defect; run an independent local SDK control."""
import hashlib
import importlib.metadata
import json
import platform
import tempfile
import urllib.request
from datetime import datetime, timezone

url = "https://docs.lancedb.com/quickstart.md"
raw = urllib.request.urlopen(url, timeout=25).read()
text = raw.decode()
line = next(line for line in text.splitlines() if line.startswith("table = db.create"))
report = {
    "checkedAt": datetime.now(timezone.utc).isoformat(),
    "source": url,
    "sourceSha256": hashlib.sha256(raw).hexdigest(),
    "runtime": platform.python_version(),
    "platform": platform.platform(),
    "packages": {p: importlib.metadata.version(p) for p in ["lancedb", "polars", "pyarrow"]},
    "check": "Compile the table-creation line exactly as delivered in Markdown, without Markdown unescaping.",
    "line": line,
}
try:
    compile(line, "served_markdown_snippet", "exec")
    report["rawSnippet"] = "compiles"
except SyntaxError as exc:
    report["rawSnippet"] = {"error": type(exc).__name__, "message": exc.msg, "offset": exc.offset}
corrected = line.replace("\\_", "_")
compile(corrected, "unescaped_snippet", "exec")
report["unescapedSnippet"] = "compiles"

# Independent control, using synthetic records rather than copying a third-party example.
import lancedb
with tempfile.TemporaryDirectory() as work:
    db = lancedb.connect(work)
    table = db.create_table("characters", data=[
        {"name": "Alpha", "vector": [0.0, 1.0], "stats": {"magic": 5}},
        {"name": "Beta", "vector": [1.0, 0.0], "stats": {"magic": 1}},
    ])
    rows = table.search([0.0, 0.9]).where("stats.magic >= 4").limit(2).to_polars().to_dicts()
    assert len(rows) == 1 and rows[0]["name"] == "Alpha"
    report["sdkControl"] = {"status": "passed", "rows": rows}
report["limits"] = [
    "An agent can reverse Markdown escapes; no universal agent failure is claimed.",
    "The browser serves code inside a custom code-group span. Its copy-button behavior was not tested.",
    "Control tests equivalent local SDK operations with synthetic data, not every original example.",
    "Only Ubuntu x86_64 / Python 3.12 was tested; no remote enterprise service or paid API used.",
]
print(json.dumps(report, indent=2))
