#!/usr/bin/env python3
"""
AgentKit Wallet Demo — Self-contained Python script
===================================================
Demonstrates an AI agent using the AgentKit wallet API:
  1. Create a wallet for an agent_id
  2. Check the balance
  3. Fund the wallet (add credits)
  4. Make a payment (charge against the wallet)
  5. Inspect transaction history

Usage:
    # With your API key directly (replace AK_LIVE_... with your key):
    python agent_wallet_demo.py --api-key AK_LIVE_...

    # To create a new wallet first (no API key needed):
    python agent_wallet_demo.py --agent-id my-agent-001 --spending-limit 50000 --initial-balance 10000

Requirements:
    pip install requests

No external dependencies beyond the standard library + requests.
"""

import argparse
import json
import sys
import uuid
from typing import Optional

# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
BASE_URL = "https://agentkit-2.polsia.app"
DEFAULT_HEADERS = {"Content-Type": "application/json"}


# ---------------------------------------------------------------------------
# Wallet API helpers
# ---------------------------------------------------------------------------

def create_wallet(agent_id: str, spending_limit_cents: int = 50_000,
                  initial_balance_cents: int = 10_000,
                  allowed_providers: list[str] | None = None) -> dict:
    """
    POST /api/wallets
    Register a new wallet for an agent. Returns wallet + raw api_key (shown once).
    """
    payload = {
        "agent_id": agent_id,
        "spending_limit_cents": spending_limit_cents,
        "initial_balance_cents": initial_balance_cents,
    }
    if allowed_providers:
        payload["allowed_providers"] = allowed_providers

    resp = _post("/api/wallets", payload)
    print(f"✓ Wallet created for agent '{agent_id}'")
    print(f"  Balance: ${resp['wallet']['current_balance_cents'] / 100:.2f}")
    print(f"  Spending limit: ${resp['wallet']['spending_limit_cents'] / 100:.2f}")
    print(f"\n  ⚠️  API KEY — save this now, it will not be shown again:")
    print(f"     {resp['api_key']}\n")
    return resp


def get_wallet(api_key: str) -> dict:
    """GET /api/wallets — get your wallet info (balance, spending limit, policies)."""
    resp = _get("/api/wallets", api_key)
    w = resp["wallet"]
    print(f"  Balance: ${w['current_balance_cents'] / 100:.2f} / "
          f"${w['spending_limit_cents'] / 100:.2f} limit")
    return resp


def credit_wallet(api_key: str, amount_cents: int) -> dict:
    """POST /api/wallets/:id/credit — add funds to your own wallet."""
    resp = _post("/api/wallets/:id/credit", {"amount_cents": amount_cents}, api_key)
    w = resp["wallet"]
    print(f"✓ Added ${amount_cents / 100:.2f} → new balance: ${w['current_balance_cents'] / 100:.2f}")
    return resp


def charge_wallet(api_key: str, provider: str, amount_cents: int,
                  idempotency_key: str | None = None) -> dict:
    """
    POST /api/pay — authorize and deduct a charge.
    Returns { status, transaction_id, balance_cents, reason? }

    policy checks run in order:
      1. provider allowlist
      2. provider daily limit
      3. wallet spending limit
      4. wallet balance

    If any check fails, status='blocked' and reason is set.
    """
    if not idempotency_key:
        idempotency_key = uuid.uuid4().hex

    payload = {
        "provider": provider,
        "amount_cents": amount_cents,
        "idempotency_key": idempotency_key,
    }

    print(f"  Charging ${amount_cents / 100:.2f} to provider '{provider}' "
          f"(idempotency_key={idempotency_key[:8]}...)")

    resp = _post("/api/pay", payload, api_key)

    if resp["status"] == "approved":
        print(f"  ✓ Approved  (tx #{resp['transaction_id']}) "
              f"→ new balance: ${resp['balance_cents'] / 100:.2f}")
    else:
        print(f"  ✗ Blocked: {resp['reason']}")

    return resp


def list_transactions(api_key: str, provider: str | None = None,
                      status: str | None = None) -> list[dict]:
    """
    GET /api/transactions — list transaction history for this wallet.
    Optional filters: ?provider=openai&status=blocked
    """
    params = {}
    if provider:
        params["provider"] = provider
    if status:
        params["status"] = status

    resp = _get("/api/transactions", api_key, params)
    txs = resp["transactions"]
    print(f"\n  Transaction history ({len(txs)} records):")
    for tx in txs:
        flag = "✓" if tx["status"] == "approved" else "✗"
        amount = f"${tx['amount_cents'] / 100:.2f}"
        reason = f" [{tx.get('reason', '')}]" if tx["status"] == "blocked" else ""
        print(f"    {flag} tx#{tx['id']}  {tx['provider']:<15} {amount:<10}{reason}")
    return txs


# ---------------------------------------------------------------------------
# Core HTTP helpers
# ---------------------------------------------------------------------------

def _post(path: str, payload: dict, api_key: str | None = None) -> dict:
    url = BASE_URL + path
    headers = dict(DEFAULT_HEADERS)
    if api_key:
        headers["X-API-Key"] = api_key

    import requests
    resp = requests.post(url, json=payload, headers=headers, timeout=15)
    _check_error(resp)
    return resp.json()


def _get(path: str, api_key: str, params: dict | None = None) -> dict:
    url = BASE_URL + path
    headers = dict(DEFAULT_HEADERS)
    headers["X-API-Key"] = api_key

    import requests
    resp = requests.get(url, headers=headers, params=params or {}, timeout=15)
    _check_error(resp)
    return resp.json()


def _check_error(resp) -> None:
    if not resp.ok:
        try:
            body = resp.json()
            msg = body.get("error", resp.text)
        except Exception:
            msg = resp.text
        sys.stderr.write(f"HTTP {resp.status_code}: {msg}\n")
        sys.exit(1)


# ---------------------------------------------------------------------------
# Demo scenarios
# ---------------------------------------------------------------------------

def demo_check_balance(api_key: str) -> None:
    """Step 1: Check current balance and wallet status."""
    print("\n[1] Checking wallet balance...")
    get_wallet(api_key)


def demo_fund_wallet(api_key: str, amount_cents: int = 25_000) -> None:
    """Step 2: Add credits to the wallet."""
    print(f"\n[2] Funding wallet with ${amount_cents / 100:.2f}...")
    credit_wallet(api_key, amount_cents)


def demo_make_payment(api_key: str) -> None:
    """Step 3: Make a series of payments (approved + blocked scenarios)."""
    print("\n[3] Making payments...")

    # Approved: allowed provider with sufficient balance
    charge_wallet(api_key, "openai", 4_20)  # $4.20

    # Approved: second allowed provider
    charge_wallet(api_key, "stripe", 1_500)  # $15.00

    # Blocked: provider not in allowlist
    charge_wallet(api_key, "anthropic", 5_00)  # $50 — not allowed

    # Blocked: insufficient balance (charge more than available)
    # First drain to near-zero
    charge_wallet(api_key, "openai", 10_000_00)  # large amount


def demo_transaction_history(api_key: str) -> None:
    """Step 4: Show full transaction log."""
    print("\n[4] Full transaction history:")
    list_transactions(api_key)


# ---------------------------------------------------------------------------
# CLI entry point
# ---------------------------------------------------------------------------

def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="AgentKit Wallet Demo — run a full agent wallet workflow in Python.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Run full demo with an existing API key:
  python agent_wallet_demo.py --api-key AK_LIVE_abcdef123456

  # Create a fresh wallet then run the demo:
  python agent_wallet_demo.py --agent-id my-agent --spending-limit 50000 --initial-balance 10000

  # Run with a specific funding amount:
  python agent_wallet_demo.py --api-key AK_LIVE_xxx --fund-amount 50000
        """,
    )

    # Existing wallet path
    g1 = parser.add_argument_group("Use existing wallet")
    g1.add_argument("--api-key", help="Your wallet API key (ak_live_...)")

    # Create wallet path
    g2 = parser.add_argument_group("Create new wallet")
    g2.add_argument("--agent-id", help="Unique agent identifier (e.g. 'my-agent-001')")
    g2.add_argument("--spending-limit", type=int, default=50_000,
                    help="Monthly spending cap in cents (default: 50000 = $500)")
    g2.add_argument("--initial-balance", type=int, default=10_000,
                    help="Starting balance in cents (default: 10000 = $100)")
    g2.add_argument("--allowed-providers", nargs="+",
                    default=["openai", "stripe"],
                    help="Allowed providers for this wallet")

    # Demo controls
    g3 = parser.add_argument_group("Demo options")
    g3.add_argument("--fund-amount", type=int, default=25_000,
                    help="Amount to fund (in cents, default: 25000 = $250)")
    g3.add_argument("--skip-payment", action="store_true",
                    help="Skip the payment demo (balance check + fund only)")

    return parser


def main() -> None:
    parser = build_parser()
    args = parser.parse_args()

    # Need either --api-key or --agent-id
    if not args.api_key and not args.agent_id:
        parser.print_help()
        print("\nError: pass --api-key (existing wallet) or --agent-id (create new wallet)")
        sys.exit(1)

    # -----------------------------------------------------------------------
    # Bootstrap: get or create the API key
    # -----------------------------------------------------------------------
    if args.api_key:
        api_key = args.api_key
        print(f"Using existing wallet (key: {api_key[:12]}...)")
    else:
        result = create_wallet(
            agent_id=args.agent_id,
            spending_limit_cents=args.spending_limit,
            initial_balance_cents=args.initial_balance,
            allowed_providers=args.allowed_providers,
        )
        api_key = result["api_key"]

    # -----------------------------------------------------------------------
    # Run the demo sequence
    # -----------------------------------------------------------------------
    print("\n" + "=" * 60)
    print("  AGENTKIT WALLET DEMO")
    print("=" * 60)

    demo_check_balance(api_key)

    if not args.skip_payment:
        demo_fund_wallet(api_key, args.fund_amount)
        demo_make_payment(api_key)
        demo_transaction_history(api_key)

    print("\n" + "=" * 60)
    print("  Demo complete.")
    print("  Your API key: " + api_key)
    print("=" * 60 + "\n")


if __name__ == "__main__":
    main()