#!/usr/bin/env python3

import argparse
import os
import os.path
import sys
import typing

from decimal import Decimal
from solana.publickey import PublicKey

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
import mango  # nopep8


def airdrop_token(
    context: mango.Context,
    wallet: mango.Wallet,
    token: mango.Token,
    faucet: typing.Optional[PublicKey],
    quantity: Decimal,
) -> typing.Sequence[str]:
    if faucet is None:
        raise Exception(f"Faucet must be specified for airdropping {token.symbol}")

    # This is a root wallet account - get the associated token account
    destination: PublicKey = mango.TokenAccount.find_or_create_token_address_to_use(
        context, wallet, wallet.address, token
    )

    signers: mango.CombinableInstructions = mango.CombinableInstructions.from_wallet(
        wallet
    )

    mango.output(f"Airdropping {quantity} {token.symbol} to {destination}")
    native_quantity = token.shift_to_native(quantity)
    airdrop = mango.build_spl_faucet_airdrop_instructions(
        token.mint, destination, faucet, native_quantity
    )

    all_instructions = signers + airdrop
    return all_instructions.execute(context)


def airdrop_sol(
    context: mango.Context, wallet: mango.Wallet, token: mango.Token, quantity: Decimal
) -> typing.Sequence[str]:
    mango.output(f"Airdropping {quantity} {token.symbol} to {wallet.address}")
    lamports = token.shift_to_native(quantity)
    response = context.client.compatible_client.request_airdrop(
        wallet.address, int(lamports)
    )
    return [response["result"]]


parser = argparse.ArgumentParser(description="mint SPL tokens to your wallet")
mango.ContextBuilder.add_command_line_parameters(parser)
mango.Wallet.add_command_line_parameters(parser)
parser.add_argument(
    "--symbol", type=str, required=True, help="token symbol to airdrop (e.g. USDC)"
)
parser.add_argument(
    "--faucet", type=PublicKey, required=False, help="public key of the faucet"
)
parser.add_argument(
    "--quantity", type=Decimal, required=True, help="quantity token to airdrop"
)
parser.add_argument(
    "--wait",
    action="store_true",
    default=False,
    help="wait until the transactions are confirmed",
)
args: argparse.Namespace = mango.parse_args(parser)

with mango.ContextBuilder.from_command_line_parameters(args) as context:
    wallet = mango.Wallet.from_command_line_parameters_or_raise(args)
    token: mango.Token = mango.token(context, args.symbol)

    # The loaded `token` variable will be from the `context`, so if it's SOL it will be
    # 'wrapped SOL' with a 1112 mint address, not regular SOL with a 1111 mint address.
    if token.symbol == mango.SolToken.symbol:
        signatures = airdrop_sol(context, wallet, token, args.quantity)
    else:
        signatures = airdrop_token(context, wallet, token, args.faucet, args.quantity)

    if args.wait:
        mango.output("Waiting on transaction signatures:")
        mango.output(mango.indent_collection_as_str(signatures, 1))
        results = mango.WebSocketTransactionMonitor.wait_for_all(
            context.client.cluster_ws_url, signatures
        )
        mango.output("Transaction results:")
        mango.output(mango.indent_collection_as_str(results, 1))
    else:
        mango.output("Transaction signatures:")
        mango.output(mango.indent_collection_as_str(signatures, 1))
