import json
from brynq.brainiac import BrainiacEngine

engine = BrainiacEngine()

def mcp_broker_brainiac_fetch(args: str) -> str:
    """Fetch and clean text from a URL. Args: url"""
    url = args.strip()
    if not url: return "Error: URL required"
    return engine.fetch_url(url)

def mcp_broker_brainiac_embed(args: str) -> str:
    """Embed knowledge. Args: JSON with content, source, optional metadata"""
    try:
        data = json.loads(args)
        return engine.embed_knowledge(
            data.get("content", ""),
            data.get("source", "unknown"),
            data.get("metadata", {})
        )
    except Exception as e:
        return f"Error: {str(e)}"

def mcp_broker_brainiac_search(args: str) -> str:
    """Semantic search the knowledge graph. Args: JSON with query, optional n_results"""
    try:
        data = json.loads(args)
        results = engine.semantic_search(
            data.get("query", ""),
            data.get("n_results", 3)
        )
        return json.dumps(results, indent=2)
    except Exception as e:
        return f"Error: {str(e)}"

TOOLS = [
    {
        "name": "brainiac_fetch_url",
        "description": "Scrape and clean raw text from a webpage. Args: URL string",
        "inputSchema": {"type": "object", "properties": {"args": {"type": "string"}}},
        "handler": mcp_broker_brainiac_fetch
    },
    {
        "name": "brainiac_embed_knowledge",
        "description": "Embed synthesized knowledge into the ChromaDB vector graph. Args: JSON with content, source.",
        "inputSchema": {"type": "object", "properties": {"args": {"type": "string"}}},
        "handler": mcp_broker_brainiac_embed
    },
    {
        "name": "brainiac_semantic_search",
        "description": "Search the federated knowledge graph. Args: JSON with query, n_results",
        "inputSchema": {"type": "object", "properties": {"args": {"type": "string"}}},
        "handler": mcp_broker_brainiac_search
    }
]
