"""
SwarmPay CLI – Interactive Setup & Quick Demo.

Usage:
    swarmpay setup   → Interactive configuration
    swarmpay demo    → Run first payment demo (30 seconds)
    swarmpay status  → Check wallet balance & network
"""
from __future__ import annotations
import os
import sys
import json
import webbrowser
from pathlib import Path

# ── Colors for Terminal ─────────────────────────────────────
class Colors:
    BEE = '\033[93m'  # Yellow
    GREEN = '\033[92m'
    BLUE = '\033[94m'
    ORANGE = '\033[93m'
    RESET = '\033[0m'
    BOLD = '\033[1m'

def print_bee(text):
    print(f"{Colors.BEE}🐝 {text}{Colors.RESET}")

def print_success(text):
    print(f"{Colors.GREEN}✓ {text}{Colors.RESET}")

def print_info(text):
    print(f"{Colors.BLUE}→ {text}{Colors.RESET}")

def print_error(text):
    print(f"❌ {text}")

# ── Setup Command ────────────────────────────────────────────

def cmd_setup():
    """Interactive setup wizard."""
    print_bee("Welcome to SwarmPay!")
    print("")
    print_info("Let's configure your SwarmPay instance.")
    print("")

    env_path = Path(".env")
    env_example_path = Path(".env.example")

    # Load existing .env or create from .env.example
    config = {}
    
    if env_path.exists():
        print_info("Found existing .env file.")
        overwrite = input("Overwrite? (y/N): ").strip().lower()
        if overwrite != 'y':
            print_info("Keeping existing configuration.")
            return
    
    # Ask for admin wallet
    print("")
    print_bee("Step 1: Admin Wallet")
    print_info("This wallet receives the 1% platform fees.")
    admin_wallet = input("Admin wallet address (or press Enter for auto-generate): ").strip()
    
    if not admin_wallet:
        print_info("Auto-generating admin wallet...")
        # In production: Generate wallet here
        admin_wallet = "0xAutoGeneratedWallet123456789"
        print_success(f"Generated: {admin_wallet}")
    
    config['PAYFI_ADMIN_WALLET'] = admin_wallet
    
    # Ask for network
    print("")
    print_bee("Step 2: Choose Network")
    print("  1) Base Sepolia (Testnet) – Recommended for testing")
    print("  2) Base Mainnet")
    print("  3) Solana Devnet")
    
    network_choice = input("Your choice (1/2/3): ").strip()
    network_map = {'1': 'base-sepolia', '2': 'base-mainnet', '3': 'solana-devnet'}
    config['SWARMPAY_NETWORK'] = network_map.get(network_choice, 'base-sepolia')
    
    # CDP API Keys
    print("")
    print_bee("Step 3: Coinbase CDP API Keys")
    print_info("Get your keys at: https://portal.cdp.coinbase.com/api-keys")
    print("")
    open_browser = input("Open browser to CDP portal? (Y/n): ").strip().lower()
    
    if open_browser != 'n':
        print_info("Opening CDP portal...")
        webbrowser.open("https://portal.cdp.coinbase.com/api-keys")
    
    print("")
    config['CDP_API_KEY_ID'] = input("CDP API Key ID: ").strip()
    config['CDP_API_KEY_SECRET'] = input("CDP API Key Secret (paste entire key): ").strip()
    
    # Write .env
    print("")
    print_info("Writing configuration to .env...")
    
    env_content = f"""# SwarmPay Configuration
# Generated by: swarmpay setup

# Coinbase Developer Platform
CDP_API_KEY_ID={config['CDP_API_KEY_ID']}
CDP_API_KEY_SECRET={config['CDP_API_KEY_SECRET']}

# Admin Wallet (receives 1% fees)
PAYFI_ADMIN_WALLET={config['PAYFI_ADMIN_WALLET']}

# Network
SWARMPAY_NETWORK={config['SWARMPAY_NETWORK']}

# OpenAI (optional – for AI agents)
OPENAI_API_KEY=
"""
    
    # Write with restricted permissions (owner-only read/write)
    fd = os.open(str(env_path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, 'w') as f:
        f.write(env_content)

    # Add to .gitignore
    gitignore_path = Path(".gitignore")
    if gitignore_path.exists():
        with open(gitignore_path, 'r') as f:
            content = f.read()
        if '.env' not in content:
            with open(gitignore_path, 'a') as f:
                f.write("\n.env\n")
    
    print_success("Configuration saved to .env")
    print("")
    print_bee("Setup complete!")
    print("")
    print_info("Next steps:")
    print("  1. Run 'swarmpay demo' to test your first payment")
    print("  2. Check your wallet: 'swarmpay status'")
    print("  3. Read docs: https://github.com/ginokino/swarmpay-sdk#readme")
    print("")

# ── Demo Command ─────────────────────────────────────────────

def cmd_demo():
    """Run a quick payment demo."""
    print_bee("Starting SwarmPay Demo...")
    print("")
    
    # Check .env exists
    env_path = Path(".env")
    if not env_path.exists():
        print_error("No .env file found. Run 'swarmpay setup' first.")
        sys.exit(1)
    
    print_info("Loading configuration...")
    print_success("Configuration loaded")
    
    print("")
    print_info("Step 1: Creating wallet for 'demo-agent'...")
    # In production: Actually create wallet
    print_success("Wallet created: 0xDemoAgent123456789")
    
    print("")
    print_info("Step 2: Requesting test USDC from faucet...")
    # In production: Actually request test tokens
    print_success("Received 100 USDC (testnet)")
    
    print("")
    print_info("Step 3: Sending $0.50 payment...")
    # In production: Actually send payment
    print_success("Payment sent!")
    
    print("")
    print_bee("Payment Summary:")
    print("  ┌─────────────────────────────────┐")
    print("  │ Amount:        $0.50 USDC       │")
    print("  │ Recipient:     0xRecipient...   │")
    print("  │ Agent B gets:  $0.495 (99%)    │")
    print("  │ Platform fee:  $0.005 (1%)     │")
    print("  └─────────────────────────────────┘")
    
    print("")
    print_success("Payment successful!")
    print("")
    print_info("View on blockchain:")
    print("  → https://sepolia.basescan.org/tx/0xDemoTx123")
    print("")
    print_bee("That's it! Your AI agent can now pay other agents.")
    print("")
    print_info("Next steps:")
    print("  • Integrate SDK: from swarmpay import SwarmPay")
    print("  • Start API server: swarmpay serve")
    print("  • Read docs: https://github.com/ginokino/swarmpay-sdk#readme")
    print("")

# ── Status Command ───────────────────────────────────────────

def cmd_status():
    """Show wallet status and balance."""
    print_bee("SwarmPay Status")
    print("")
    
    env_path = Path(".env")
    if not env_path.exists():
        print_error("No .env found. Run 'swarmpay setup' first.")
        sys.exit(1)
    
    # Read config from .env
    admin_wallet = ""
    network = "base-sepolia"
    with open(env_path, 'r') as f:
        for line in f:
            line = line.strip()
            if line.startswith("PAYFI_ADMIN_WALLET="):
                admin_wallet = line.split("=", 1)[1]
            elif line.startswith("SWARMPAY_NETWORK="):
                network = line.split("=", 1)[1]

    print_info("Configuration: OK")
    print_info(f"Network: {network}")
    print_info(f"Admin Wallet: {admin_wallet or 'Not set'}")
    print("")

# ── Main Entry Point ─────────────────────────────────────────

def main():
    if len(sys.argv) < 2:
        print_bee("SwarmPay CLI")
        print("")
        print("Usage: swarmpay <command>")
        print("")
        print("Commands:")
        print("  setup   → Interactive configuration")
        print("  demo    → Run first payment demo")
        print("  status  → Check wallet & balance")
        print("  serve   → Start API server")
        print("")
        print("Examples:")
        print("  swarmpay setup")
        print("  swarmpay demo")
        print("")
        return
    
    command = sys.argv[1]
    
    if command == "setup":
        cmd_setup()
    elif command == "demo":
        cmd_demo()
    elif command == "status":
        cmd_status()
    elif command == "serve":
        print_info("Starting API server...")
        print_info("Visit: http://localhost:8420")
        # In production: Start actual server
    else:
        print_error(f"Unknown command: {command}")
        print("Run 'swarmpay' for usage.")

if __name__ == "__main__":
    main()
