#!/usr/bin/env python3

import argparse
from getpass import getpass
from pyinvest import auth, config, accounts

parser = argparse.ArgumentParser()
parser.add_argument('--quantity', '-q', type=int, action='append', required=True)
parser.add_argument('--symbol', '-s', type=str, action='append', required=True)
parser.add_argument('--instruction', '-i', type=str, action='append', required=True)
parser.add_argument('--config', '-c', type=str, default='$HOME/config/pyinvest.json')
args = parser.parse_args()

password = getpass()

info = config.Config(args.config)

access_token = auth.authenticate(info.client_id, info.redirect, info.username, password)

td_ameritrade = accounts.TDAmeritradeClient(access_token, info.account_id)
account_info = td_ameritrade.get_account_info()
positions = td_ameritrade.get_positions()

total_account_value = account_info['currentBalances']['liquidationValue']
available_cash = account_info['currentBalances']['cashAvailableForTrading']

for quantity, symbol, instruction in zip(args.quantity, args.symbol, args.instruction):
    quote = td_ameritrade.get_quote(symbol)

    current_price = quote['regularMarketLastPrice']

    if available_cash < quantity * current_price:
        print("Insufficient funds for trade.")
        print(f"Cash available: {available_cash}")
        print(f"Current price for {symbol}: {current_price}")
        exit()

    try:
        res = td_ameritrade.place_market_order(quantity, symbol, instruction)
        print(f"Order to {instruction.lower()} {quantity} share(s) of {symbol} placed successfully.")
    except requests.exceptions.RequestException as e:
        print("Something went wrong. Please try again.")

