#!/usr/bin/env python3
"""Exercise deterministic Vercy retrieval on 5,000 synthetic objects."""

from __future__ import annotations

import json
import platform
import sys
import tempfile
import time
from pathlib import Path


HERE = Path(__file__).resolve().parent
SITE = HERE.parents[1]
SCRIPTS = SITE / "skills" / "vercy" / "scripts"
sys.path.insert(0, str(SCRIPTS))
from build_index import build  # noqa: E402
from query_dimension import query  # noqa: E402


COUNT = 5000


def write(path: Path, value: object) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, separators=(",", ":")), encoding="utf-8")


def main() -> int:
    with tempfile.TemporaryDirectory(prefix="vercy-scale-") as raw:
        root = Path(raw)
        write(root / "policies" / "conflict-resolution.yaml", {"format": "vercy-conflict-policy", "schemaVersion": "1.0.0", "dimension": "benchmark.scale", "truthMode": "bitemporal-assertions", "precedence": ["explicit-supersedes", "higher-authority-rank"], "tieBreak": "latest-recorded-same-authority", "unresolved": "return-contested-set-never-guess", "validTimeBoundary": "half-open"})
        started = time.perf_counter()
        for index in range(COUNT):
            oid = f"scale.asset.{index:05d}"
            write(root / "data" / "objects" / f"object-{index:05d}.json", {"recordType": "object", "schemaVersion": "1.0.0", "recordId": f"scale.object.{index:05d}.r1", "objectId": oid, "objectType": "equipment.synthetic", "name": f"Calibration asset {index:05d}", "recordedAt": "2026-01-01T00:00:00Z", "previousRecordId": None, "state": "active", "provenance": {"source": "benchmark"}})
            write(root / "data" / "facts" / f"fact-{index:05d}.json", {"recordType": "fact", "schemaVersion": "1.0.0", "factId": f"scale.fact.{index:05d}", "subjectId": oid, "path": "inspection.score", "value": index % 101, "validFrom": "2026-01-01T00:00:00Z", "validTo": None, "recordedAt": "2026-01-01T00:00:00Z", "supersedes": [], "status": "asserted", "provenance": {"source": "benchmark"}, "authority": {"source": "benchmark", "rank": 1}, "masterSystem": "benchmark"})
            if index:
                write(root / "data" / "relations" / f"relation-{index:05d}.json", {"recordType": "relation", "schemaVersion": "1.0.0", "relationId": f"scale.relation.{index:05d}", "relationType": "nextTo", "sourceId": oid, "targetId": f"scale.asset.{index - 1:05d}", "validFrom": "2026-01-01T00:00:00Z", "validTo": None, "recordedAt": "2026-01-01T00:00:00Z", "status": "asserted", "provenance": {"source": "benchmark"}})
        generation = time.perf_counter() - started
        started = time.perf_counter()
        manifest = build(root)
        indexing = time.perf_counter() - started
        started = time.perf_counter()
        by_text = query(root, text="Calibration asset 04999", limit=5)
        by_relation = query(root, related_to="scale.asset.04999", limit=5)
        by_time = query(root, object_id="scale.asset.04999", valid_at="2026-02-01T00:00:00Z", known_at="2026-02-01T00:00:00Z", limit=5)
        querying = time.perf_counter() - started
        assertions = {
            "textFound": any(item.get("objectId") == "scale.asset.04999" for item in by_text["records"]),
            "relationFound": len(by_relation["relations"]) == 1,
            "factFound": bool(by_time["facts"] and by_time["facts"][0]["facts"][0]["value"] == 4999 % 101),
        }
        result = {
            "benchmark": "vercy-index-scale-v1", "runAt": "2026-09-05T00:00:00Z",
            "python": platform.python_version(), "platform": platform.platform(),
            "objects": COUNT, "facts": COUNT, "relations": COUNT - 1,
            "generatedSeconds": round(generation, 6), "indexedSeconds": round(indexing, 6),
            "threeQueriesSeconds": round(querying, 6), "recordCounts": manifest["recordCounts"],
            "assertions": assertions, "passed": all(assertions.values()),
            "note": "Synthetic local filesystem run; timings are descriptive, not a cross-machine SLA."
        }
        (HERE / "result.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
        print(json.dumps(result, indent=2))
        return 0 if result["passed"] else 1


if __name__ == "__main__":
    raise SystemExit(main())
