"""Run a small synthetic OSK v5.0.0 store/search/source-read proof.

Usage: python demo.py /path/to/osk-system > result.json
Use Python with the repository's requirements installed. No network is used.
The source repository is only read; all engine writes go to a temporary fixture.
"""
from __future__ import annotations

import io
import json
import os
from pathlib import Path
import platform
import subprocess
import sys
import tempfile
import zipfile
from datetime import datetime, timezone


COMMIT = "75c24c065bfd3e4a77eea87f59af72bb8a6bfa3e"


def main():
    if len(sys.argv) != 2:
        raise SystemExit("Usage: python demo.py /path/to/osk-system")
    source = Path(sys.argv[1]).resolve()
    # Export tracked, committed public code rather than a user's current vault.
    revision = subprocess.check_output(
        ["git", "-C", str(source), "rev-parse", "v5.0.0^{commit}"], text=True
    ).strip()
    assert revision == COMMIT, "Unexpected v5.0.0 commit; refuse to run"
    archive = subprocess.check_output(
        ["git", "-C", str(source), "archive", "--format=zip", COMMIT, "_governance/_engine"]
    )
    with tempfile.TemporaryDirectory(prefix="osk-synthetic-proof-") as temporary:
        sandbox = Path(temporary)
        with zipfile.ZipFile(io.BytesIO(archive)) as exported:
            for member in exported.infolist():
                target = (sandbox / member.filename).resolve()
                assert target.is_relative_to(sandbox.resolve()), "Unsafe archive member"
            exported.extractall(sandbox)
        engine = sandbox / "_governance/_engine"
        vault = sandbox / "synthetic-vault"
        runtime = sandbox / "runtime"
        runtime.mkdir()
        os.environ.update(OSK_VAULT_ROOT=str(vault), OSK_UPDATE_CHECK="0",
                          PYTHONDONTWRITEBYTECODE="1", TMP=str(runtime),
                          TEMP=str(runtime), TMPDIR=str(runtime))
        tempfile.tempdir = str(runtime)
        sys.dont_write_bytecode = True
        sys.path.insert(0, str(engine))
        from osk import core, graph, validate, write
        import mcp_server as server

        assert core.ROOT == vault.resolve(), "Isolation failed"
        validate.make_mini_vault(vault)
        observations = []

        def store(title, summary, body, edges=None):
            answer = write.create_node(title, summary, body, "gpt-6.1-sol",
                                       space="00_Scope/W1", edges=edges)
            assert answer.get("ok"), answer
            assert not answer.get("dangling"), answer
            assert not answer.get("placement_error"), answer
            observations.append({"operation": "create_node", "result": answer})
            return answer

        source_note = store(
            "Synthetic requirement", "Fictional photo app requirement; not a customer interview",
            "# Synthetic requirement\n\nThis is invented demonstration data.\n"
            "A fictional photo app should find existing photos without a network connection.\n"
            "Its first prototype has no cloud upload requirement.\n"
        )
        decision = store(
            "Local photo index", "Use an on-device index to support airplane mode",
            "# Decision\n\nBuild a local index so photo search works in airplane mode.\n\n"
            "# Reason\n\nThe synthetic requirement prioritizes disconnected use.\n\n"
            "# Revisit when\n\nRevisit if a verified requirement for cross-device sync appears.\n",
            edges={"derived-from": source_note["id"]},
        )
        for title, body in (
            ("Synthetic color choice", "Use green for the fictional interface accent."),
            ("Synthetic release checklist", "Check typography and keyboard focus before release."),
            ("Synthetic support hours", "Publish a contact email for questions about the prototype."),
        ):
            store(title, "Unrelated synthetic control note", body)

        query = "airplane mode"
        hits = server.search(query, 5)
        observations.append({"operation": "search", "query": query, "result": hits})
        assert hits and hits[0]["id"] == decision["id"], "Expected decision not ranked first"
        retrieved = server.read_node(hits[0]["title"])
        observations.append({"operation": "read_node", "input": hits[0]["title"], "result": retrieved})
        assert "airplane mode" in retrieved["body"]
        index = graph.Index()
        parsed = index.node(vault / retrieved["path"])
        references = parsed.edges("derived-from")
        assert len(references) == 1
        evidence = server.read_node(references[0])
        observations.append({"operation": "read_node", "input": references[0], "result": evidence})
        assert evidence["id"] == source_note["id"]
        assert "without a network connection" in evidence["body"]
        negative = server.search("unmatchedtokenxyz", 5)
        assert negative == [], "Absent token should not produce a hit"
        observations.append({"operation": "search", "query": "unmatchedtokenxyz", "result": negative})

        result = {
            "status": "PASS",
            "recorded_at_utc": datetime.now(timezone.utc).isoformat(),
            "source_repository": "https://github.com/lpaiu-cs/osk-system",
            "source_ref": "v5.0.0", "source_commit": COMMIT,
            "python": platform.python_version(),
            "scenario": "Synthetic stored decision -> lexical search -> read decision -> follow derived-from -> read source",
            "tested": ["Engine creates and stores five synthetic notes in an isolated fixture",
                       "Actual BM25 search ranks the relevant decision first for one chosen query",
                       "Actual read_node returns the persisted decision and its linked source",
                       "One unrelated query returns no results"],
            "not_tested": ["Claude or any other model performance", "MCP transport or client integration",
                           "Conversation capture or autonomous memory growth", "Customer adoption or willingness to pay",
                           "General retrieval accuracy, latency, or improvement over a baseline"],
            "observations": observations,
        }
        serialized = json.dumps(result, ensure_ascii=False, indent=2)
        assert str(source) not in serialized and str(sandbox) not in serialized, "Private path in output"
        print(serialized)


if __name__ == "__main__":
    main()
