import pytest
import os
import httpx
import json
from conftest import BASE_URL

def _headers():
    return {
        "X-User-ID": os.environ.get("SYNC_TEST_USER_ID", "")
    }

@pytest.mark.slow
def test_mcp_dispatch():
    """
    Test calling the 'dispatch' tool via MCP.
    """
    node_id = os.getenv("SYNC_TEST_NODE1", "test-node-1")
    user_id = os.getenv("SYNC_TEST_USER_ID", "")
    
    with httpx.Client(timeout=10.0) as client:
        # 1. Call tools/call for dispatch
        payload = {
            "jsonrpc": "2.0",
            "id": "test-dispatch-1",
            "method": "tools/call",
            "params": {
                "name": "dispatch",
                "arguments": {
                    "node_id": node_id,
                    "command": "echo 'Hello from MCP'"
                }
            }
        }
        
        r = client.post(f"{BASE_URL}/mcp/?token={user_id}", json=payload)
        assert r.status_code == 200, f"MCP call failed: {r.text}"
        
        res_data = r.json()
        assert "result" in res_data
        result = res_data["result"]
        
        assert "content" in result
        content_block = result["content"][0]
        assert content_block["type"] == "text"
        
        text_val = content_block["text"]
        data = json.loads(text_val)
        assert data["status"] == "accepted"
        assert "task_id" in data
        print(f"[test] MCP Dispatch success, task_id: {data['task_id']}")
