import json
from brynq import agent_sandbox

def mcp_broker_sandbox_create(args: str) -> str:
    """Create a sandbox. Args: JSON containing agent_id, optional initial_level."""
    try:
        data = json.loads(args)
        res = agent_sandbox.create_sandbox(data.get('agent_id'), data.get('initial_level', 'intern'))
        return json.dumps(res)
    except Exception as e:
        return json.dumps({"error": str(e)})

def mcp_broker_sandbox_check(args: str) -> str:
    """Check permission. Args: JSON containing agent_id, action, resource."""
    try:
        data = json.loads(args)
        allowed, msg = agent_sandbox.check_permission(data.get('agent_id'), data.get('action'), data.get('resource'))
        return json.dumps({"allowed": allowed, "message": msg})
    except Exception as e:
        return json.dumps({"error": str(e)})

def mcp_broker_sandbox_promote(args: str) -> str:
    """Promote agent. Args: JSON containing agent_id, new_level."""
    try:
        data = json.loads(args)
        res = agent_sandbox.promote(data.get('agent_id'), data.get('new_level'))
        return json.dumps(res)
    except Exception as e:
        return json.dumps({"error": str(e)})

TOOLS = [
    {
        "name": "broker_sandbox_create",
        "description": "Create a sandbox. Args: JSON containing agent_id, initial_level",
        "inputSchema": {"type": "object", "properties": {"args": {"type": "string"}}},
        "handler": mcp_broker_sandbox_create
    },
    {
        "name": "broker_sandbox_check",
        "description": "Check sandbox permission. Args: JSON containing agent_id, action, resource",
        "inputSchema": {"type": "object", "properties": {"args": {"type": "string"}}},
        "handler": mcp_broker_sandbox_check
    },
    {
        "name": "broker_sandbox_promote",
        "description": "Promote agent trust level. Args: JSON containing agent_id, new_level",
        "inputSchema": {"type": "object", "properties": {"args": {"type": "string"}}},
        "handler": mcp_broker_sandbox_promote
    }
]
