from __future__ import annotations

import json

from synaptopus.demo_export import export_demo_artifacts, export_xor_demo_artifacts


def test_demo_export_writes_all_artifacts(tmp_path) -> None:
    artifacts = export_xor_demo_artifacts(tmp_path)

    graph = json.loads(artifacts["graph"].read_text(encoding="utf-8"))
    trace = json.loads(artifacts["trace"].read_text(encoding="utf-8"))
    report = json.loads(artifacts["report"].read_text(encoding="utf-8"))
    manifest = json.loads(artifacts["manifest"].read_text(encoding="utf-8"))

    assert graph["artifact_type"] == "graph_schema"
    assert graph["payload"]["nodes"][0]["node_type"] == "generator"
    assert trace["artifact_type"] == "execution_trace"
    assert trace["payload"]["accepted"][0]["candidate"] == [0, 1]
    assert report["artifact_type"] == "run_report"
    assert report["payload"]["parameters"]["example"] == "xor_novelty"
    assert report["payload"]["accepted_count"] == 2
    assert manifest["artifacts"][0]["artifact_type"] == "graph_schema"


def test_demo_export_can_target_parity_pressure_demo(tmp_path) -> None:
    artifacts = export_demo_artifacts(
        tmp_path,
        demo_name="parity_pressure",
        accepted_count=3,
        max_attempts_per_accept=12,
    )

    trace = json.loads(artifacts["trace"].read_text(encoding="utf-8"))
    report = json.loads(artifacts["report"].read_text(encoding="utf-8"))

    assert report["payload"]["parameters"]["example"] == "parity_pressure"
    assert report["payload"]["accepted_count"] == 3
    assert trace["payload"]["attempts"][2]["metadata"]["category"]["delta_vigilance"] is True


def test_demo_export_can_write_and_resume_from_snapshot(tmp_path) -> None:
    artifacts = export_demo_artifacts(
        tmp_path,
        demo_name="parity_pressure",
        accepted_count=4,
        max_attempts_per_accept=12,
        snapshot_after_accepted=2,
    )

    manifest = json.loads(artifacts["manifest"].read_text(encoding="utf-8"))
    snapshot = json.loads(artifacts["snapshot"].read_text(encoding="utf-8"))
    report = json.loads(artifacts["report"].read_text(encoding="utf-8"))

    assert manifest["artifacts"][-1]["artifact_type"] == "demo_snapshot"
    assert snapshot["artifact_type"] == "demo_snapshot"
    assert snapshot["payload"]["record"]["final_state"]["attempts"] >= 2
    assert report["payload"]["accepted_count"] == 4
