import unittest
import time
import sys
import os

# Add mesh-sdk to path
sys.path.append(os.path.join(os.getcwd(), "mesh-sdk"))

from mesh_core.server_engine import MeshServerCore
from mesh_core.node_engine import MeshNodeCore
from mesh_core.transport_mock import MockMeshTransport
from mesh_core import agent_pb2

class TestMeshCore(unittest.TestCase):
    def test_server_registration(self):
        server = MeshServerCore()
        online_nodes = []
        server.on_node_online = lambda record: online_nodes.append(record.node_id)
        
        transport = MockMeshTransport("test-node")
        server.register_node("test-node", "user-1", {"desc": "test"}, transport)
        
        self.assertIn("test-node", online_nodes)
        self.assertEqual(len(server.list_nodes()), 1)
        self.assertEqual(server.get_node("test-node").user_id, "user-1")

    def test_node_lifecycle(self):
        transport = MockMeshTransport("node-1")
        node = MeshNodeCore("node-1", transport)
        
        received_tasks = []
        node.on_task = lambda task: received_tasks.append(task)
        
        # Mock handshake to always succeed
        transport.handshake = lambda: True
        
        node.start()
        self.assertTrue(transport.is_connected())
        
        # Simulate inbound message from server
        msg = agent_pb2.ServerTaskMessage(task_request=agent_pb2.TaskRequest(task_id="t1", payload_json="{}"))
        transport.simulate_server_message(msg)
        
        self.assertEqual(len(received_tasks), 1)
        self.assertEqual(received_tasks[0].task_id, "t1")
        
        node.stop()
        self.assertFalse(transport.is_connected())

if __name__ == "__main__":
    unittest.main()
