# -*- coding: utf-8 -*-
"""Operational demo of the Sparse Model Nexus operator algebra.

Runs each of the four operators (⊕ ∘ ▷ ⊗) on real prompts with the trained
quanta and writes a JSON transcript that the published demo.html renders.
"""
import os, json, time, sys
from sparse_nexus import Nexus, QUANTA

def main():
    t0 = time.time()
    nexus = Nexus()
    transcript = {"base": "distilgpt2", "quanta": QUANTA,
                  "generated": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
                  "runs": []}

    # ▷ route — predicate picks the right specialist per prompt
    for prompt in ["def reverse_linked_list(head):",
                   "The function of insulin in glucose metabolism is",
                   "Here is a short note about the weather:"]:
        r = nexus.route(prompt)
        r["prompt"] = prompt
        transcript["runs"].append(r)

    # ⊕ mixture — blend code + shared at varying widths on a neutral prompt
    for w in ({"code_specialist": 1.0, "shared_common": 0.0},          # ~pure code (null-expert on shared)
              {"code_specialist": 0.5, "shared_common": 0.5},
              {"code_specialist": 0.7, "biomed_specialist": 0.3}):
        r = nexus.mixture("Explain the following clearly:", w)
        r["prompt"] = "Explain the following clearly:"
        transcript["runs"].append(r)

    # ∘ sequential — shared frames, then code specializes (non-commutative)
    r = nexus.sequential("Write a helper.", ["shared_common", "code_specialist"])
    transcript["runs"].append(r)

    # ⊗ merge — task-arithmetic merge of all three into one deployable quantum
    r = nexus.merge(QUANTA, name="omni_quantum",
                    prompt="A concise, well-structured explanation:")
    transcript["runs"].append(r)

    transcript["elapsed_s"] = round(time.time() - t0, 1)
    out = os.path.join(os.path.dirname(__file__), "demo_transcript.json")
    with open(out, "w", encoding="utf-8") as f:
        json.dump(transcript, f, indent=2, ensure_ascii=False)
    print(json.dumps(transcript, indent=2, ensure_ascii=False))
    print(f"\nwrote {out} in {transcript['elapsed_s']}s", file=sys.stderr)

if __name__ == "__main__":
    main()
