#!/usr/bin/env python3
"""
Check OKX demo account positions and recent orders.

Usage:
    uv run python check_demo_account.py
"""
import sys
from pathlib import Path
from datetime import datetime, timezone

sys.path.insert(0, str(Path(__file__).parent))

from live_trading.config import OKXConfig
import ccxt


def main():
    """Check demo account status."""
    config = OKXConfig()
    
    print(f"\n{'='*60}")
    print(f"  OKX Demo Account Check")
    print(f"{'='*60}")
    print(f"  Demo Mode: {config.demo_mode}")
    print(f"  API Key:   {config.api_key[:8]}..." if config.api_key else "  API Key: NOT SET")
    print(f"{'='*60}\n")
    
    exchange = ccxt.okx({
        'apiKey': config.api_key,
        'secret': config.secret,
        'password': config.password,
        'sandbox': config.demo_mode,
        'options': {'defaultType': 'swap'},
        'enableRateLimit': True,
    })
    
    # Check balance
    print("--- BALANCE ---")
    balance = exchange.fetch_balance()
    usdt = balance.get('USDT', {})
    print(f"USDT Total: {usdt.get('total', 0):.2f}")
    print(f"USDT Free:  {usdt.get('free', 0):.2f}")
    print(f"USDT Used:  {usdt.get('used', 0):.2f}")
    
    # Check all balances
    print("\n--- ALL NON-ZERO BALANCES ---")
    for currency, data in balance.items():
        if isinstance(data, dict) and data.get('total', 0) > 0:
            print(f"{currency}: total={data.get('total', 0):.6f}, free={data.get('free', 0):.6f}")
    
    # Check open positions
    print("\n--- OPEN POSITIONS ---")
    positions = exchange.fetch_positions()
    open_positions = [p for p in positions if abs(float(p.get('contracts', 0))) > 0]
    
    if open_positions:
        for pos in open_positions:
            print(f"  {pos['symbol']}: {pos['side']} {pos['contracts']} contracts @ {pos.get('entryPrice', 'N/A')}")
            print(f"    Unrealized PnL: {pos.get('unrealizedPnl', 'N/A')}")
    else:
        print("  No open positions")
    
    # Check recent orders (last 50)
    print("\n--- RECENT ORDERS (last 24h) ---")
    try:
        # Fetch closed orders for AVAX
        orders = exchange.fetch_orders('AVAX/USDT:USDT', limit=20)
        if orders:
            for order in orders[-10:]:  # Last 10
                ts = datetime.fromtimestamp(order['timestamp']/1000, tz=timezone.utc)
                print(f"  [{ts.strftime('%H:%M:%S')}] {order['side'].upper()} {order['amount']} AVAX @ {order.get('average', order.get('price', 'market'))}")
                print(f"    Status: {order['status']}, Filled: {order.get('filled', 0)}, ID: {order['id']}")
        else:
            print("  No recent AVAX orders")
    except Exception as e:
        print(f"  Could not fetch orders: {e}")
    
    # Check order history more broadly
    print("\n--- ORDER HISTORY (AVAX) ---")
    try:
        # Try fetching my trades
        trades = exchange.fetch_my_trades('AVAX/USDT:USDT', limit=10)
        if trades:
            for trade in trades[-5:]:
                ts = datetime.fromtimestamp(trade['timestamp']/1000, tz=timezone.utc)
                print(f"  [{ts.strftime('%Y-%m-%d %H:%M:%S')}] {trade['side'].upper()} {trade['amount']} @ {trade['price']}")
                print(f"    Fee: {trade.get('fee', {}).get('cost', 'N/A')} {trade.get('fee', {}).get('currency', '')}")
        else:
            print("  No recent AVAX trades")
    except Exception as e:
        print(f"  Could not fetch trades: {e}")
    
    print(f"\n{'='*60}\n")


if __name__ == "__main__":
    main()
