#!/usr/bin/env python
"""
Bulk Labs Faucet Setup Application

This app automates the testnet account setup process:
1. Whitelists a public key for faucet access
2. Requests specified amount in testnet margin
3. Verifies the margin was correctly credited to the account

Usage:
    python faucet_setup_app.py --auth <admin_key> --key <target_pubkey> --amount 1000000

    Or with environment variables:
    export BULK_AUTH_KEY="your_admin_private_key"
    python faucet_setup_app.py --key <target_pubkey> --amount 1000000
"""

import sys
import time
import argparse
from typing import Optional

sys.path.insert(0, '../api')
from bulk_api import BulkHttpClient



def fund(
    private_key: str,
    base_url: str,
    amount: float = 1_000_000.0,
) -> dict:
    """
    Complete faucet setup workflow for a testnet account

    Args:
        private_key: Target account's private key to whitelist and fund
        amount: Amount of USDC to request (default $1M)
        base_url: API base URL (default testnet)

    Returns:
        Dictionary containing:
        - target_key: The target account's private key
        - whitelist_response: Response from whitelist operation
        - faucet_response: Response from faucet request
        - account_state: Full account state after funding
        - margin_verified: Boolean indicating if margin matches expected amount
        - actual_margin: The actual margin balance received
    """

    # Initialize admin client with auth key
    print(f"Initializing HTTP client with admin key...")
    admin_client = BulkHttpClient(base_url=base_url, private_key=private_key)

    pubkey = admin_client.signer.public_key
    print(f"Target public key: {pubkey}")
    print()

    # Step 2: Request faucet funds
    print("=" * 70)
    print(f"STEP 2: Requesting ${amount:,.2f} from faucet")
    print("=" * 70)

    try:
        faucet_response = admin_client.request_faucet(
            user=pubkey,
            amount=amount
        )
        print(f"✓ Faucet response: {faucet_response}")
    except Exception as e:
        print(f"✗ Faucet request failed: {e}")
        return {
            "target_key": pubkey,
            "error": f"Faucet request failed: {e}",
            "step": "faucet"
        }


def main():
    """Main entry point for the application"""

    # Setup argument parser
    parser = argparse.ArgumentParser(
        description='Bulk Labs Testnet Faucet Setup - Whitelist, fund, and verify testnet accounts',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
            Examples:
              # Fund account with default $1M
              %(prog)s --auth <admin_key> --key <target_pubkey>
            
              # Fund with custom amount
              %(prog)s --auth <admin_key> --key <target_pubkey> --amount 500000
            
              # Use environment variable for auth key
              export BULK_AUTH_KEY='your_admin_key'
              %(prog)s --key <target_pubkey> --amount 1000000
        """
    )

    parser.add_argument(
        '--key',
        type=str,
        required=True,
        help='Target private key (base58) to fund'
    )

    parser.add_argument(
        '--amount',
        type=float,
        default=1_000_000.0,
        help='Amount of USDC to request (default: 1000000)'
    )

    parser.add_argument(
        '--url',
        type=str,
        default='https://exchange-api2.bulk.trade/api/v1',
        help='API base URL (default: testnet URL)'
    )

    args = parser.parse_args()

    # Get auth key from args or environment
    print()
    print("=" * 70)
    print("BULK LABS TESTNET FAUCET SETUP")
    print("=" * 70)
    print()

    # Run the setup
    result = fund(
        private_key=args.key,
        amount=args.amount,
        base_url=args.url
    )

    # Print final summary
    print()
    print("=" * 70)
    print("FINAL SUMMARY")
    print("=" * 70)


if __name__ == "__main__":
    main()
