import json
from brynq import federation

def mcp_broker_fed_init(args: str) -> str:
    """Init local federation instance. Args: JSON containing instance_id, public_url, and name."""
    try:
        data = json.loads(args)
        res = federation.init_instance(data.get('instance_id'), data.get('public_url'), data.get('name'))
        return json.dumps(res)
    except Exception as e:
        return json.dumps({"error": str(e)})

def mcp_broker_fed_add_peer(args: str) -> str:
    """Add a remote peer to federation. Args: JSON containing peer_id, url, token."""
    try:
        data = json.loads(args)
        res = federation.add_peer(data.get('peer_id'), data.get('url'), data.get('token'))
        return json.dumps(res)
    except Exception as e:
        return json.dumps({"error": str(e)})

def mcp_broker_fed_status(args: str) -> str:
    """Get federation instance status."""
    try:
        res = federation.get_instance()
        return json.dumps(res)
    except Exception as e:
        return json.dumps({"error": str(e)})

TOOLS = [
    {
        "name": "broker_fed_init",
        "description": "Initialize local federation node. Args: JSON with instance_id, public_url, name",
        "inputSchema": {"type": "object", "properties": {"args": {"type": "string"}}},
        "handler": mcp_broker_fed_init
    },
    {
        "name": "broker_fed_add_peer",
        "description": "Add a remote peer. Args: JSON with peer_id, url, token",
        "inputSchema": {"type": "object", "properties": {"args": {"type": "string"}}},
        "handler": mcp_broker_fed_add_peer
    },
    {
        "name": "broker_fed_status",
        "description": "Get local federation node status. No args required.",
        "inputSchema": {"type": "object", "properties": {"args": {"type": "string"}}},
        "handler": mcp_broker_fed_status
    }
]
