#!/usr/bin/env python3

import argparse
import os
import os.path
import sys

from solana.publickey import PublicKey

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


parser = argparse.ArgumentParser(description="redeems PnL for a Mango account")
mango.ContextBuilder.add_command_line_parameters(parser)
mango.Wallet.add_command_line_parameters(parser)
parser.add_argument(
    "--market", type=str, help="perp market symbol to redeem PnL (e.g. ETH-PERP)"
)
parser.add_argument(
    "--all",
    action="store_true",
    default=False,
    help="redeem all MNGO in all perp markets in the account",
)
parser.add_argument(
    "--account-address",
    type=PublicKey,
    help="address of the specific account to use, if more than one available",
)
parser.add_argument(
    "--dry-run",
    action="store_true",
    default=False,
    help="runs as read-only and does not perform any transactions",
)
parser.add_argument(
    "--wait",
    action="store_true",
    default=False,
    help="wait until the transactions are confirmed",
)
args: argparse.Namespace = mango.parse_args(parser)

if (not args.all) and (args.market is None):
    raise Exception(
        "Must specify either an individual market (using --market) or use --all for all markets"
    )

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, context.group_address)
    cache = mango.Cache.load(context, group.cache)
    account = mango.Account.load_for_owner_by_address(
        context, wallet.address, group, args.account_address
    )

    if args.all:
        signatures = account.redeem_all_perp_pnl(context, wallet, group, cache)
    else:
        group_slots = [
            gs
            for gs in group.slots
            if mango.Market.symbols_match(gs.perp_market_symbol, args.market)
        ]
        if len(group_slots) != 1:
            raise Exception(
                f"Could not find perp market slot with symbol '{args.market}'"
            )

        group_slot = group_slots[0]
        slot = account.slots[group_slot.index]
        perp_market_cache = group.perp_market_cache_from_cache(
            cache, slot.base_instrument
        )
        if perp_market_cache is None:
            raise Exception(
                f"Could not find perp market cache for {slot.base_instrument.symbol}"
            )

        price = group.token_price_from_cache(cache, slot.base_instrument)
        signatures = account.redeem_pnl_for_perp_market(
            context, wallet, group, slot, perp_market_cache, price
        )

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