"""
OpenAI Function Calling Tools für SwarmPay.

Damit können GPT-4 Agents direkt über Function Calling
Services kaufen und bezahlen.

Usage:
    from swarmpay.openai_tools import SWARMPAY_TOOLS, handle_swarmpay_call

    response = openai.chat.completions.create(
        model="gpt-4o",
        messages=[...],
        tools=SWARMPAY_TOOLS,
    )
"""
from __future__ import annotations
import json

SWARMPAY_TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "swarmpay_buy_service",
            "description": "Kauft einen Service von einem anderen KI-Agenten über die SwarmPay-Plattform. "
                           "Findet automatisch den günstigsten Anbieter und bezahlt in USDC.",
            "parameters": {
                "type": "object",
                "properties": {
                    "service_type": {
                        "type": "string",
                        "description": "Art des gewünschten Services",
                        "enum": ["text-analysis", "translation", "image-generation",
                                 "code-review", "data-scraping", "summarization"],
                    },
                    "max_price_usd": {
                        "type": "number",
                        "description": "Maximaler Preis in USD den der Agent zahlen will",
                    },
                },
                "required": ["service_type"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "swarmpay_list_services",
            "description": "Zeigt alle verfügbaren Services auf der SwarmPay-Plattform an.",
            "parameters": {
                "type": "object",
                "properties": {},
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "swarmpay_check_balance",
            "description": "Prüft den USDC-Kontostand der Agenten-Wallet.",
            "parameters": {
                "type": "object",
                "properties": {},
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "swarmpay_register_service",
            "description": "Registriert einen neuen Service den dieser Agent anbieten kann.",
            "parameters": {
                "type": "object",
                "properties": {
                    "service_type": {
                        "type": "string",
                        "description": "Art des angebotenen Services",
                    },
                    "price_usd": {
                        "type": "number",
                        "description": "Preis pro Aufruf in USD",
                    },
                    "description": {
                        "type": "string",
                        "description": "Beschreibung was der Service macht",
                    },
                },
                "required": ["service_type", "price_usd", "description"],
            },
        },
    },
]


def handle_swarmpay_call(function_name: str, arguments: dict,
                      swarmpay_client, wallet) -> str:
    """
    Verarbeitet einen OpenAI Function Call.

    Args:
        function_name: Name der aufgerufenen Funktion
        arguments: Argumente als Dict
        swarmpay_client: SwarmPay-Instanz
        wallet: AgentWallet-Instanz

    Returns:
        JSON-String mit dem Ergebnis
    """
    if function_name == "swarmpay_buy_service":
        service_type = arguments["service_type"]
        max_price = arguments.get("max_price_usd", float("inf"))

        provider = swarmpay_client.find_cheapest(service_type)
        if not provider:
            return json.dumps({"error": f"Kein Anbieter für '{service_type}' gefunden"})

        if provider["price_usd"] > max_price:
            return json.dumps({
                "error": f"Günstigster Anbieter kostet ${provider['price_usd']}, "
                         f"aber Maximum ist ${max_price}"
            })

        result = swarmpay_client.buy_service(wallet, service_type)
        if "error" in result:
            return json.dumps(result)
        payment = result["payment"]
        return json.dumps({
            "success": payment.success,
            "service": result["provider"]["service_type"],
            "price": payment.amount_usd,
            "fee": payment.fee_usd,
            "provider": result["provider"]["description"],
        })

    elif function_name == "swarmpay_list_services":
        services = swarmpay_client.registry.list_all()
        return json.dumps({"services": [
            {"type": s["service_type"], "price": s["price_usd"],
             "description": s.get("description", "")}
            for s in services
        ]})

    elif function_name == "swarmpay_check_balance":
        return json.dumps({
            "balance_usdc": wallet.balance("USDC"),
            "wallet_address": wallet.address,
        })

    elif function_name == "swarmpay_register_service":
        service_id = swarmpay_client.register_service(
            wallet=wallet,
            service_type=arguments["service_type"],
            price_usd=arguments["price_usd"],
            description=arguments.get("description", ""),
        )
        return json.dumps({"service_id": service_id, "status": "registered"})

    return json.dumps({"error": f"Unbekannte Funktion: {function_name}"})
