#!/usr/bin/env python3
"""
AgentKit Walkthrough — One script, end to end.
===============================================
Walks through the full AgentKit lifecycle:

  Step 1  Create a wallet  (no auth)
  Step 2  Save the API key
  Step 3  Check balance
  Step 4  Fund the wallet
  Step 5  Make a tool purchase (charge)

Run:
    python walkthrough.py

Or with overrides (replace values as needed):
    python walkthrough.py --agent-id my-agent-001 --spending-limit 50000 --fund-amount 2500

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

import argparse
import json
import sys
import urllib.request
import urllib.error

# ---------------------------------------------------------------------------
# Config — change BASE_URL here for a self-hosted instance
# ---------------------------------------------------------------------------
BASE_URL = "https://agentkit-2.polsia.app"


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

def api_request(method: str, path: str, payload: dict | None = None,
                 api_key: str | None = None) -> dict:
    """Fire a JSON REST call. Raises SystemExit on error."""
    url = f"{BASE_URL}{path}"
    body = json.dumps(payload or {}).encode() if payload else None

    headers = {"Content-Type": "application/json", "Accept": "application/json"}
    if api_key:
        headers["X-API-Key"] = api_key

    req = urllib.request.Request(url, data=body, headers=headers, method=method)
    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            return json.loads(resp.read())
    except urllib.error.HTTPError as e:
        try:
            err_body = json.loads(e.read())
            msg = err_body.get("error", err_body.get("message", e.reason))
        except Exception:
            msg = e.reason
        sys.stderr.write(f"[!] HTTP {e.code}: {msg}\n")
        sys.exit(1)


def post(path: str, payload: dict | None = None, api_key: str | None = None) -> dict:
    return api_request("POST", path, payload, api_key)


def get(path: str, api_key: str | None = None) -> dict:
    return api_request("GET", path, None, api_key)


# ---------------------------------------------------------------------------
# Steps
# ---------------------------------------------------------------------------

def create_wallet(agent_id: str, spending_limit_cents: int,
                  initial_balance_cents: int, allowed_providers: list[str]):
    """
    Step 1 — Create a wallet (no authentication required).
    Returns (wallet_id, raw_api_key).
    """
    print("\n[Step 1] Create wallet")
    print(f"  agent_id:              {agent_id}")
    print(f"  spending_limit_cents:  {spending_limit_cents}  (${spending_limit_cents / 100:.2f})")
    print(f"  initial_balance_cents: {initial_balance_cents} (${initial_balance_cents / 100:.2f})")
    print(f"  allowed_providers:     {allowed_providers}")

    resp = post("/api/wallets", {
        "agent_id": agent_id,
        "spending_limit_cents": spending_limit_cents,
        "initial_balance_cents": initial_balance_cents,
        "allowed_providers": allowed_providers,
    })

    wallet_id = resp["wallet"]["id"]
    api_key = resp["api_key"]
    balance = resp["wallet"]["current_balance_cents"]

    print(f"\n  ✓ Wallet created (id={wallet_id})")
    print(f"  ✓ Initial balance: ${balance / 100:.2f}")
    print(f"\n  ⚠️  Save your API key — it's only shown once:")
    print(f"     {api_key}")

    return wallet_id, api_key


def check_balance(api_key: str):
    """Step 2 — Verify wallet balance via the authenticated endpoint."""
    print("\n[Step 2] Check balance")
    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 w["current_balance_cents"]


def fund_wallet(wallet_id: int, api_key: str, amount_cents: int):
    """Step 3 — Add funds to the wallet via the credit endpoint."""
    print(f"\n[Step 3] Fund wallet (+${amount_cents / 100:.2f})")
    resp = post(f"/api/wallets/{wallet_id}/credit",
                {"amount_cents": amount_cents}, api_key)
    new_balance = resp["balance_cents"]
    print(f"  ✓ New balance: ${new_balance / 100:.2f}")
    return new_balance


def make_tool_purchase(api_key: str, provider: str, amount_cents: int):
    """
    Step 4 — Make a charge against the wallet.
    The policy engine checks provider allowlist + balance before approving.
    """
    print(f"\n[Step 4] Make tool purchase")
    print(f"  provider:     {provider}")
    print(f"  amount_cents: {amount_cents} (${amount_cents / 100:.2f})")

    resp = post("/api/pay", {
        "provider": provider,
        "amount_cents": amount_cents,
        "idempotency_key": "walkthrough-demo-001",
    }, api_key)

    status = resp.get("status", "unknown")
    balance = resp.get("balance_cents", 0)

    if status == "approved":
        print(f"  ✓ Approved  (transaction #{resp.get('transaction_id', '?')})")
        print(f"  ✓ Remaining balance: ${balance / 100:.2f}")
    else:
        print(f"  ✗ Blocked: {resp.get('reason', 'unknown reason')}")

    return resp


def main():
    parser = argparse.ArgumentParser(
        description="AgentKit walkthrough — full wallet lifecycle in one script.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument("--agent-id", default="my-agent-001",
                        help="Unique agent identifier (default: my-agent-001)")
    parser.add_argument("--spending-limit", type=int, default=50_000,
                        help="Spending cap in cents (default: 50000 = $500)")
    parser.add_argument("--initial-balance", type=int, default=10_000,
                        help="Starting balance in cents (default: 10000 = $100)")
    parser.add_argument("--fund-amount", type=int, default=25_000,
                        help="Amount to fund in cents (default: 25000 = $250)")
    parser.add_argument("--provider", default="openai",
                        help="Provider to charge (default: openai)")
    parser.add_argument("--charge-amount", type=int, default=4_20,
                        help="Charge amount in cents (default: 420 = $4.20)")
    parser.add_argument("--allowed-providers", nargs="+",
                        default=["openai", "stripe"],
                        help="Allowed providers (default: openai stripe)")
    args = parser.parse_args()

    print("=" * 60)
    print("  AgentKit Walkthrough")
    print(f"  Base URL: {BASE_URL}")
    print("=" * 60)

    # Step 1
    wallet_id, api_key = create_wallet(
        agent_id=args.agent_id,
        spending_limit_cents=args.spending_limit,
        initial_balance_cents=args.initial_balance,
        allowed_providers=args.allowed_providers,
    )

    # Step 2
    check_balance(api_key)

    # Step 3
    fund_wallet(wallet_id, api_key, args.fund_amount)

    # Step 4
    make_tool_purchase(api_key, args.provider, args.charge_amount)

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


# ---------------------------------------------------------------------------
# EXPECTED OUTPUT
# ---------------------------------------------------------------------------
"""
After running:

  python walkthrough.py

You should see:

================================================================
  AgentKit Walkthrough
  Base URL: https://agentkit-2.polsia.app
================================================================

[Step 1] Create wallet
  agent_id:              my-agent-001
  spending_limit_cents:  50000  ($500.00)
  initial_balance_cents: 10000 ($100.00)
  allowed_providers:     ['openai', 'stripe']

  ✓ Wallet created (id=13)
  ✓ Initial balance: $100.00

  ⚠️  Save your API key — it's only shown once:
     ak_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

[Step 2] Check balance
  ✓ Balance: $100.00 / $500.00 limit

[Step 3] Fund wallet (+$250.00)
  ✓ New balance: $350.00

[Step 4] Make tool purchase
  provider:     openai
  amount_cents: 420 ($4.20)
  ✓ Approved  (transaction #4892)
  ✓ Remaining balance: $345.80

================================================================
  Walkthrough complete.
  Your API key (keep this): ak_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
================================================================

Troubleshooting:
  HTTP 401    — Invalid or expired API key. Re-create the wallet.
  HTTP 403    — Provider not in wallet's allowed_providers list.
  HTTP 402    — Insufficient balance. Fund the wallet first (/credit).
  HTTP 422    — Missing required field (check the error message).
  HTTP 409    — Idempotency key already used (safe to retry without it).
  Connection error — Check your network. Ensure BASE_URL is reachable.
"""
# ---------------------------------------------------------------------------

if __name__ == "__main__":
    main()