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_list_nodes():
    user_id = os.getenv("SYNC_TEST_USER_ID", "")
    with httpx.Client(timeout=10.0) as client:
        payload = {
            "jsonrpc": "2.0",
            "id": "test-list-nodes",
            "method": "tools/call",
            "params": {"name": "list_nodes", "arguments": {}}
        }
        r = client.post(f"{BASE_URL}/mcp/?token={user_id}", json=payload)
        assert r.status_code == 200
        res = r.json()["result"]
        text = res["content"][0]["text"]
        data = json.loads(text)
        assert "nodes" in data
        print(f"[test] MCP list_nodes success: {len(data['nodes'])} nodes")

@pytest.mark.slow
def test_mcp_get_node_details():
    user_id = os.getenv("SYNC_TEST_USER_ID", "")
    node_id = os.getenv("SYNC_TEST_NODE1", "test-node-1")
    with httpx.Client(timeout=10.0) as client:
        payload = {
            "jsonrpc": "2.0",
            "id": "test-get-node-details",
            "method": "tools/call",
            "params": {"name": "get_node_details", "arguments": {"node_id": node_id}}
        }
        r = client.post(f"{BASE_URL}/mcp/?token={user_id}", json=payload)
        assert r.status_code == 200
        res = r.json()["result"]
        text = res["content"][0]["text"]
        data = json.loads(text)
        assert data["node_id"] == node_id
        print(f"[test] MCP get_node_details success for {node_id}")

@pytest.mark.slow
def test_mcp_list_agents():
    user_id = os.getenv("SYNC_TEST_USER_ID", "")
    with httpx.Client(timeout=10.0) as client:
        payload = {
            "jsonrpc": "2.0",
            "id": "test-list-agents",
            "method": "tools/call",
            "params": {"name": "list_agents", "arguments": {}}
        }
        r = client.post(f"{BASE_URL}/mcp/?token={user_id}", json=payload)
        assert r.status_code == 200
        res = r.json()["result"]
        text = res["content"][0]["text"]
        data = json.loads(text)
        assert "agents" in data
        print(f"[test] MCP list_agents success: {len(data['agents'])} agents")

@pytest.mark.slow
def test_mcp_list_skills():
    user_id = os.getenv("SYNC_TEST_USER_ID", "")
    with httpx.Client(timeout=10.0) as client:
        payload = {
            "jsonrpc": "2.0",
            "id": "test-list-skills",
            "method": "tools/call",
            "params": {"name": "list_skills", "arguments": {}}
        }
        r = client.post(f"{BASE_URL}/mcp/?token={user_id}", json=payload)
        assert r.status_code == 200
        res = r.json()["result"]
        text = res["content"][0]["text"]
        data = json.loads(text)
        assert "skills" in data
        print(f"[test] MCP list_skills success: {len(data['skills'])} skills")
