#!/usr/bin/env python3

import argparse
import os
import os.path
import sys

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

parser = argparse.ArgumentParser(
    description="Ensure a Mango account exists for the wallet and group."
)
mango.ContextBuilder.add_command_line_parameters(parser)
mango.Wallet.add_command_line_parameters(parser)
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)
    group = mango.Group.load(context)
    accounts = mango.Account.load_all_for_owner(context, wallet.address, group)

    if len(accounts) > 0:
        mango.output(
            f"At least one account already exists for group {group.address} and wallet {wallet.address}"
        )
        mango.output(accounts)
    else:
        signers: mango.CombinableInstructions = (
            mango.CombinableInstructions.from_wallet(wallet)
        )
        init = mango.build_mango_create_account_instructions(context, wallet, group)
        all_instructions = signers + init
        signatures = all_instructions.execute(context)

        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))

        updated_accounts = mango.Account.load_all_for_owner(
            context, wallet.address, group
        )
        mango.output(updated_accounts)
