#!/usr/bin/env python3
"""Test the blackboard graph."""
import os
import tempfile

# Use temp dir for graph
tmpdir = tempfile.mkdtemp(prefix="bbg-test-")
os.environ["BLACKBOARD_GRAPH_PATH"] = f"{tmpdir}/graph.json"

from mcp_blackboard_graph.main import load_graph, save_graph, get_node, ensure_node_fields


def test_load_empty():
    graph = load_graph()
    assert "nodes" in graph
    assert "root" in graph["nodes"]
    print("  load empty: ok")


def test_add_node():
    graph = load_graph()
    graph["nodes"]["child1"] = {
        "id": "child1",
        "parents": ["root"],
        "children": [],
        "status": "active",
        "notes": [],
        "messages": [],
        "data": {}
    }
    graph["nodes"]["root"]["children"].append("child1")
    save_graph(graph)

    graph = load_graph()
    node = get_node(graph, "child1")
    assert node is not None
    assert node["id"] == "child1"
    assert "root" in node["parents"]
    print("  add node: ok")


def test_dag_multiple_parents():
    graph = load_graph()
    # Add second parent
    graph["nodes"]["parent2"] = {
        "id": "parent2",
        "parents": ["root"],
        "children": ["child1"],
        "status": "active",
        "notes": [],
        "messages": [],
        "data": {}
    }
    graph["nodes"]["root"]["children"].append("parent2")
    graph["nodes"]["child1"]["parents"].append("parent2")
    save_graph(graph)

    graph = load_graph()
    node = get_node(graph, "child1")
    assert len(node["parents"]) == 2
    assert "root" in node["parents"]
    assert "parent2" in node["parents"]
    print("  dag multiple parents: ok")


def test_notes_and_messages():
    graph = load_graph()
    node = get_node(graph, "child1")
    ensure_node_fields(node)
    node["notes"].append("test note")
    node["messages"].append({"from": "agent1", "text": "hello", "time": "now"})
    save_graph(graph)

    graph = load_graph()
    node = get_node(graph, "child1")
    assert len(node["notes"]) == 1
    assert len(node["messages"]) == 1
    print("  notes and messages: ok")


def test_data():
    graph = load_graph()
    node = get_node(graph, "child1")
    ensure_node_fields(node)
    node["data"]["key"] = "value"
    node["data"]["count"] = 42
    save_graph(graph)

    graph = load_graph()
    node = get_node(graph, "child1")
    assert node["data"]["key"] == "value"
    assert node["data"]["count"] == 42
    print("  data: ok")


if __name__ == "__main__":
    tests = [test_load_empty, test_add_node, test_dag_multiple_parents, test_notes_and_messages, test_data]
    for t in tests:
        print(f"{t.__name__}:")
        t()
    print(f"\nAll {len(tests)} tests passed!")
