#!/usr/bin/env python3

import argparse
import os
import sys

from decimal import Decimal

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

parser = argparse.ArgumentParser(
    description="Unwraps Wrapped SOL to Pure SOL and adds it to the wallet account."
)
mango.ContextBuilder.add_command_line_parameters(parser)
mango.Wallet.add_command_line_parameters(parser)
parser.add_argument(
    "--quantity", type=Decimal, required=True, help="quantity of SOL to unwrap"
)
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)
    wrapped_sol: mango.Token = mango.token(context, "SOL")
    largest_token_account = mango.TokenAccount.fetch_largest_for_owner_and_token(
        context, wallet.address, wrapped_sol
    )
    if largest_token_account is None:
        raise Exception(
            f"No {wrapped_sol.name} accounts found for owner {wallet.address}."
        )

    signers: mango.CombinableInstructions = mango.CombinableInstructions.from_signers(
        [wallet.keypair]
    )
    create_instructions = mango.build_spl_create_account_instructions(
        context, wallet, wrapped_sol
    )
    wrapped_sol_address = create_instructions.signers[0].public_key

    unwrap_instructions = mango.build_spl_transfer_tokens_instructions(
        context,
        wallet,
        wrapped_sol,
        largest_token_account.address,
        wrapped_sol_address,
        args.quantity,
    )
    close_instructions = mango.build_spl_close_account_instructions(
        context, wallet, wrapped_sol_address
    )

    all_instructions = (
        signers + create_instructions + unwrap_instructions + close_instructions
    )

    mango.output("Unwrapping SOL:")
    mango.output(f"    Temporary account: {wrapped_sol_address}")
    mango.output(f"    Source: {largest_token_account.address}")
    mango.output(f"    Destination: {wallet.address}")

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