#!/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 entropy  # nopep8

parser = argparse.ArgumentParser(description="Cancels a specific order on a market.")
entropy.ContextBuilder.add_command_line_parameters(parser)
entropy.Wallet.add_command_line_parameters(parser)
parser.add_argument(
    "--market", type=str, required=True, help="market symbol to use (e.g. ETH/USDC)"
)
parser.add_argument(
    "--id",
    type=int,
    help="order ID of the order to cancel (either --client-id must be specified, or both --id and --side must be specified",
)
parser.add_argument(
    "--client-id",
    type=int,
    help="client ID of the order to cancel (either --client-id must be specified, or both --id and --side must be specified",
)
parser.add_argument(
    "--side",
    type=entropy.Side,
    default=entropy.Side.BUY,
    choices=list(entropy.Side),
    help="whether the order to cancel is a BUY or a SELL (either --client-id must be specified, or both --id and --side must be specified",
)
parser.add_argument(
    "--account-address",
    type=PublicKey,
    help="address of the specific account to use, if more than one available",
)
parser.add_argument(
    "--ok-if-missing",
    action="store_true",
    default=False,
    help="if supported by market type (PERP-only for now) will not error if the ID does not exist",
)
parser.add_argument(
    "--wait",
    action="store_true",
    default=False,
    help="wait until the transactions are confirmed",
)
parser.add_argument(
    "--dry-run",
    action="store_true",
    default=False,
    help="runs as read-only and does not perform any transactions",
)
args: argparse.Namespace = entropy.parse_args(parser)

with entropy.ContextBuilder.from_command_line_parameters(args) as context:
    wallet = entropy.Wallet.from_command_line_parameters_or_raise(args)
    group = entropy.Group.load(context, context.group_address)
    account = entropy.Account.load_for_owner_by_address(
        context, wallet.address, group, args.account_address
    )

    market_operations = entropy.operations(
        context, wallet, account, args.market, args.dry_run
    )

    order = entropy.Order.from_ids(id=args.id, client_id=args.client_id, side=args.side)
    signatures = market_operations.cancel_order(order, ok_if_missing=args.ok_if_missing)

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