"""Imperium Universal x402 / MPP / MCP Python Client SDK (https://x402broker.com/sdk/imperium.py)"""
import json, urllib.request

class ImperiumClient:
    def __init__(self, api_key: str = "", broker_url: str = "https://x402broker.com"):
        self.api_key = api_key
        self.broker_url = broker_url.rstrip("/")

    def execute(self, tool: str, input_value: str) -> dict:
        headers = {"Content-Type": "application/json", "User-Agent": "ImperiumSDK-Py/1.0"}
        if self.api_key:
            headers["Authorization"] = f"Bearer {self.api_key}"
            headers["X-Agent-Id"] = self.api_key
        payload = {
            "jsonrpc": "2.0", "id": 1, "method": "tools/call",
            "params": {"name": "execute_marketplace_tool", "arguments": {"target_tool": tool, "input_value": input_value}}
        }
        req = urllib.request.Request(f"{self.broker_url}/mcp/x402-broker", data=json.dumps(payload).encode(), headers=headers, method="POST")
        with urllib.request.urlopen(req, timeout=30) as resp:
            raw = json.loads(resp.read().decode())
            return json.loads(raw["result"]["content"][0]["text"])

    def workflow(self, bundle_id: str, target: str) -> dict:
        headers = {"Content-Type": "application/json", "User-Agent": "ImperiumSDK-Py/1.0"}
        if self.api_key:
            headers["Authorization"] = f"Bearer {self.api_key}"
        payload = {
            "jsonrpc": "2.0", "id": 2, "method": "tools/call",
            "params": {"name": "execute_workflow_bundle", "arguments": {"bundle_id": bundle_id, "target": target}}
        }
        req = urllib.request.Request(f"{self.broker_url}/mcp/x402-broker", data=json.dumps(payload).encode(), headers=headers, method="POST")
        with urllib.request.urlopen(req, timeout=30) as resp:
            raw = json.loads(resp.read().decode())
            return json.loads(raw["result"]["content"][0]["text"])
