#!/usr/bin/env python3
"""
AgentKit + LangChain Integration Example
=========================================
Shows how to wrap AgentKit's /api/pay endpoint as a LangChain tool
so your agent can authorize and deduct payments autonomously.

Install:
    pip install langchain langchain-openai requests

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

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

import os
import uuid
import requests
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langchain.agents import create_openai_tools_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

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


# ---------------------------------------------------------------------------
# AgentKit tool
# ---------------------------------------------------------------------------

@tool
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 (LangChain ≥ 0.2 pattern)
# ---------------------------------------------------------------------------

def build_agent() -> AgentExecutor:
    llm = ChatOpenAI(model="gpt-4o-mini", temperature=0, api_key=OPENAI_API_KEY)
    tools = [pay_provider]

    prompt = ChatPromptTemplate.from_messages([
        ("system", "You are a helpful AI agent. When asked to pay for something, "
                   "use the pay_provider tool to authorize the charge."),
        ("human", "{input}"),
        MessagesPlaceholder(variable_name="agent_scratchpad"),
    ])

    agent = create_openai_tools_agent(llm, tools, prompt)
    return AgentExecutor(agent=agent, tools=tools, verbose=True)


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

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

    executor = build_agent()
    result = executor.invoke({"input": "Pay openai $4.20 for an API call."})

    print("\n" + "=" * 60)
    print("  Agent output:")
    print(f"  {result['output']}")
    print("=" * 60 + "\n")


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

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

> Entering new AgentExecutor chain...
Invoking: `pay_provider` with `{'provider': 'openai', 'amount_cents': 420}`

status=approved  transaction_id=4912  balance_cents=34580  ($345.80 remaining)
I've successfully paid OpenAI $4.20 for the API call.

> Finished chain.

================================================================
  Agent output:
  I've successfully paid OpenAI $4.20 for the API call.
================================================================

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()
