import json
from brynq import workflow_engine

def mcp_broker_we_create(args: str) -> str:
    """Create a workflow. Args: JSON containing name, steps (list of dicts)."""
    try:
        data = json.loads(args)
        res = workflow_engine.create_workflow(data.get('name', 'workflow'), data.get('steps', []))
        return json.dumps(res)
    except Exception as e:
        return json.dumps({"error": str(e)})

def mcp_broker_we_start(args: str) -> str:
    """Start a workflow. Args: workflow_id"""
    try:
        res = workflow_engine.start_workflow(args.strip())
        return json.dumps(res)
    except Exception as e:
        return json.dumps({"error": str(e)})

def mcp_broker_we_ready(args: str) -> str:
    """Get ready steps. Args: workflow_id"""
    try:
        res = workflow_engine.get_ready_steps(args.strip())
        return json.dumps({"ready_steps": res})
    except Exception as e:
        return json.dumps({"error": str(e)})

def mcp_broker_we_complete(args: str) -> str:
    """Complete a step. Args: JSON containing workflow_id, step_id, optional outputs."""
    try:
        data = json.loads(args)
        res = workflow_engine.complete_step(data.get('workflow_id'), data.get('step_id'), data.get('outputs'))
        return json.dumps(res)
    except Exception as e:
        return json.dumps({"error": str(e)})

TOOLS = [
    {
        "name": "broker_we_create",
        "description": "Create a workflow. Args: JSON with name, steps",
        "inputSchema": {"type": "object", "properties": {"args": {"type": "string"}}},
        "handler": mcp_broker_we_create
    },
    {
        "name": "broker_we_start",
        "description": "Start a workflow. Args: workflow_id",
        "inputSchema": {"type": "object", "properties": {"args": {"type": "string"}}},
        "handler": mcp_broker_we_start
    },
    {
        "name": "broker_we_ready",
        "description": "Get ready steps. Args: workflow_id",
        "inputSchema": {"type": "object", "properties": {"args": {"type": "string"}}},
        "handler": mcp_broker_we_ready
    },
    {
        "name": "broker_we_complete",
        "description": "Complete a step. Args: JSON with workflow_id, step_id, outputs",
        "inputSchema": {"type": "object", "properties": {"args": {"type": "string"}}},
        "handler": mcp_broker_we_complete
    }
]
