#!/usr/bin/env python3

import argparse
import logging
import os
import os.path
import sys
import time
import traceback

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

parser = argparse.ArgumentParser(description="Cranks all openorders in the market.")
mango.ContextBuilder.add_command_line_parameters(parser)
mango.Wallet.add_command_line_parameters(parser)
parser.add_argument(
    "--market", type=str, required=True, help="market symbol to crank (e.g. ETH/USDC)"
)
parser.add_argument(
    "--limit",
    type=Decimal,
    default=Decimal(32),
    help="maximum number of events to be processed",
)
parser.add_argument(
    "--pulse-interval",
    type=float,
    help="if specified, run in a loop pausing this number of seconds between each crank",
)
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",
)
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, context.group_address)
    account = mango.Account.load_for_owner_by_address(
        context, wallet.address, group, args.account_address
    )

    logging.info(f"Wallet address: {wallet.address}")

    market_operations = mango.operations(
        context, wallet, account, args.market, args.dry_run
    )
    if args.pulse_interval is None:
        crank = market_operations.crank(args.limit)
        mango.output(crank)
    else:
        while True:
            try:
                crank = market_operations.crank(args.limit)
                mango.output(crank)
                time.sleep(args.pulse_interval)
            except Exception as exception:
                logging.error(f"Pulse action failed: {traceback.format_exc()}")
                mango.output(exception)

logging.info("Crank completed.")
