#!/usr/bin/env python3
"""
Manual test script for live trading on Binance testnet.
Run from project root: python test_live_manual.py
"""
import sys
import os

# Add src to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

# Set testnet credentials
os.environ['BRIGHTER_BINANCE_TESTNET_API_KEY'] = '7QXpkltLNwh9mMoDwJWMaecyhUrnjjGY4B2i3wIOhTlQnD9ggWgFI2n5OwDBeIwd'
os.environ['BRIGHTER_BINANCE_TESTNET_API_SECRET'] = 'wy7ziNcepoB0OrjJtaViVa17bFQmPgaXP95tTsCzWHViM5s5Dz1JzI45Hq0clqXC'

from Exchange import Exchange
from brokers.live_broker import LiveBroker
from brokers import OrderSide, OrderType

def main():
    print("=" * 60)
    print("LIVE TRADING MANUAL TEST - BINANCE TESTNET")
    print("=" * 60)

    # Create exchange connection
    print("\n1. Connecting to Binance testnet...")
    api_keys = {
        'key': os.environ['BRIGHTER_BINANCE_TESTNET_API_KEY'],
        'secret': os.environ['BRIGHTER_BINANCE_TESTNET_API_SECRET']
    }

    exchange = Exchange(
        name='binance',
        api_keys=api_keys,
        exchange_id='binance',
        testnet=True
    )

    print(f"   Connected: {exchange.configured}")
    print(f"   Testnet mode: {exchange.testnet}")

    # Create live broker
    print("\n2. Creating LiveBroker...")
    broker = LiveBroker(
        exchange=exchange,
        testnet=True,
        initial_balance=0.0,  # Will sync from exchange
        commission=0.001
    )

    # Connect and sync
    print("\n3. Connecting broker to exchange...")
    connected = broker.connect()
    print(f"   Connected: {connected}")

    # Get balance
    print("\n4. Checking balance...")
    balance = broker.get_balance()
    print(f"   USDT Balance: {balance}")

    # Get current price
    print("\n5. Getting BTC/USDT price...")
    price = broker.get_current_price('BTC/USDT')
    print(f"   Current price: ${price:,.2f}")

    # Place a small test order
    print("\n6. Placing test order...")
    print("   Order: BUY 0.001 BTC (market order)")

    confirm = input("\n   Press ENTER to place order, or 'q' to quit: ")
    if confirm.lower() == 'q':
        print("   Cancelled.")
        return

    result = broker.place_order(
        symbol='BTC/USDT',
        side=OrderSide.BUY,
        order_type=OrderType.MARKET,
        size=0.001
    )

    print(f"\n   Order result:")
    print(f"   - Success: {result.success}")
    print(f"   - Order ID: {result.order_id}")
    print(f"   - Status: {result.status}")
    print(f"   - Filled qty: {result.filled_qty}")
    print(f"   - Filled price: ${result.filled_price:,.2f}" if result.filled_price else "   - Filled price: N/A")
    print(f"   - Message: {result.message}")

    if result.success:
        print("\n7. Checking updated balance...")
        broker.sync_balance()
        new_balance = broker.get_balance()
        print(f"   New USDT Balance: {new_balance}")
        print(f"   Cost: ~${0.001 * price:,.2f}")

    print("\n" + "=" * 60)
    print("TEST COMPLETE")
    print("=" * 60)

if __name__ == '__main__':
    main()
