#!/usr/bin/env python3
"""
AgentKit + AutoGen Integration Example
========================================
Shows how to register AgentKit's /api/pay endpoint as a callable function
inside an AutoGen ConversableAgent pair so the agent can authorize payments.

Install:
    pip install pyautogen requests

Run:
    export AGENTKIT_API_KEY=ak_live_...
    export OPENAI_API_KEY=sk-...
    python autogen_agent.py

Expected output is shown at the bottom of this file under EXPECTED OUTPUT.
"""

import os
import uuid
import requests
import autogen

# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
BASE_URL = "https://agentkit-2.polsia.app"
AGENTKIT_API_KEY = os.environ["AGENTKIT_API_KEY"]
OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]

LLM_CONFIG = {
    "config_list": [{"model": "gpt-4o-mini", "api_key": OPENAI_API_KEY}],
    "temperature": 0,
}


# ---------------------------------------------------------------------------
# AgentKit function
# ---------------------------------------------------------------------------

def pay_provider(provider: str, amount_cents: int) -> str:
    """
    Authorize and deduct a payment from the agent's AgentKit wallet.

    Args:
        provider: The provider to charge (e.g. 'openai', 'stripe').
        amount_cents: The amount to charge in cents (e.g. 420 = $4.20).

    Returns:
        A string summarising the transaction result.
    """
    resp = requests.post(
        f"{BASE_URL}/api/pay",
        headers={"X-API-Key": AGENTKIT_API_KEY, "Content-Type": "application/json"},
        json={
            "provider": provider,
            "amount_cents": amount_cents,
            "idempotency_key": uuid.uuid4().hex,
        },
        timeout=15,
    )
    data = resp.json()
    status = data.get("status", "unknown")
    if status == "approved":
        balance = data.get("balance_cents", 0)
        txn_id = data.get("transaction_id", "?")
        return (
            f"status=approved  transaction_id={txn_id}  "
            f"balance_cents={balance}  (${balance / 100:.2f} remaining)"
        )
    reason = data.get("reason", data.get("error", "unknown"))
    return f"status={status}  reason={reason}"


# ---------------------------------------------------------------------------
# Agent setup
# ---------------------------------------------------------------------------

def build_agents():
    assistant = autogen.ConversableAgent(
        name="assistant",
        system_message=(
            "You are a helpful AI agent. When asked to pay for something, "
            "call pay_provider with the correct provider and amount_cents."
        ),
        llm_config=LLM_CONFIG,
    )

    user_proxy = autogen.ConversableAgent(
        name="user",
        human_input_mode="NEVER",
        max_consecutive_auto_reply=3,
        is_termination_msg=lambda msg: "TERMINATE" in msg.get("content", ""),
    )

    # Register the function so the assistant can call it and user_proxy executes it
    autogen.register_function(
        pay_provider,
        caller=assistant,
        executor=user_proxy,
        name="pay_provider",
        description="Authorize and deduct a payment from the AgentKit wallet.",
    )

    return assistant, user_proxy


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def main():
    print("=" * 60)
    print("  AgentKit + AutoGen Demo")
    print(f"  Base URL: {BASE_URL}")
    print("=" * 60 + "\n")

    assistant, user_proxy = build_agents()
    user_proxy.initiate_chat(
        assistant,
        message="Pay openai 420 cents for an API call.",
        max_turns=3,
    )

    print("\n" + "=" * 60)
    print("  Chat complete.")
    print("=" * 60 + "\n")


# ---------------------------------------------------------------------------
# EXPECTED OUTPUT
# ---------------------------------------------------------------------------
"""
After running (with valid keys and a funded wallet):

================================================================
  AgentKit + AutoGen Demo
  Base URL: https://agentkit-2.polsia.app
================================================================

user (to assistant):
Pay openai 420 cents for an API call.

assistant (to user):
***** Suggested tool call: pay_provider *****
Arguments:
{"provider": "openai", "amount_cents": 420}
*********************************************

user (to assistant):
***** Response from calling tool "pay_provider" *****
status=approved  transaction_id=4913  balance_cents=34160  ($341.60 remaining)
*****************************************************

assistant (to user):
The payment of 420 cents to OpenAI was approved. Remaining balance: $341.60. TERMINATE

================================================================
  Chat complete.
================================================================

Troubleshooting:
  HTTP 401 — Invalid or missing AGENTKIT_API_KEY.
  HTTP 403 — Provider not in wallet's allowed_providers list.
  HTTP 402 — Insufficient balance. Fund the wallet first.
  HTTP 422 — Missing required field (check the error message).
"""
# ---------------------------------------------------------------------------

if __name__ == "__main__":
    main()
