#!/usr/bin/env python3
"""
浪浪AI $500实盘启动脚本

使用方法:
    python start_live.py              # 启动全自动交易
    python start_live.py --test       # 先测试连接，不交易
    python start_live.py --monitor    # 只监控推送信号，不自动下单
"""

import os
import sys

# 加载 .env 配置
env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
if os.path.exists(env_path):
    with open(env_path) as f:
        for line in f:
            line = line.strip()
            if '=' in line and not line.startswith('#'):
                k, v = line.split('=', 1)
                os.environ[k.strip()] = v.strip()

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))


def test_connections():
    """测试所有连接"""
    print("=" * 50)
    print("  浪浪AI 连接测试")
    print("=" * 50)

    # 1. Telegram
    print("\n[1] Telegram...")
    from langlang_ai.notify.telegram_bot import TelegramNotifier
    notifier = TelegramNotifier()
    if notifier.enabled:
        ok = notifier.send_sync("🔧 浪浪AI 连接测试...")
        print(f"  {'✓ 连接成功' if ok else '✗ 发送失败'}")
    else:
        print("  ✗ 未配置 (检查.env文件)")

    # 2. Binance
    print("\n[2] Binance Futures...")
    try:
        from langlang_ai.execution.binance_client import BinanceClient
        client = BinanceClient.from_env()
        balance = client.get_balance()
        positions = client.get_positions()
        print(f"  ✓ 连接成功")
        print(f"  USDT余额: ${balance:,.2f}")
        print(f"  活跃持仓: {len(positions)}个")

        if positions:
            for p in positions:
                print(f"    {p['symbol']} {p['side']} qty={p['quantity']} "
                      f"PnL=${p['unrealized_pnl']:+,.2f}")

        # 测试杠杆设置
        try:
            client.set_leverage('BTCUSDT', 10)
            print(f"  杠杆设置: ✓")
        except Exception as e:
            print(f"  杠杆设置: ✗ ({e})")
            print(f"  → 检查API是否开启了合约交易权限")

        return balance

    except Exception as e:
        print(f"  ✗ 连接失败: {e}")
        print(f"  → 检查API Key和Secret是否正确")
        print(f"  → 检查是否开通了合约交易")
        return 0


def main():
    mode = sys.argv[1] if len(sys.argv) > 1 else ''

    if mode == '--test':
        balance = test_connections()
        if balance > 0:
            print(f"\n  一切就绪！余额 ${balance:,.2f}")
            print(f"  运行 python start_live.py 启动交易")
        return

    if mode == '--monitor':
        print("启动信号监控模式（不自动下单）...")
        os.system(f"{sys.executable} main.py --balance 500 --db langlang_live.db")
        return

    # 全自动交易模式
    print("=" * 50)
    print("  浪浪AI $500 全自动交易")
    print("=" * 50)
    print()
    print("  ⚠️  这是真金白银的实盘交易")
    print("  系统会自动: 开仓 / 挂止损 / trailing / 平仓")
    print("  所有操作会通过Telegram通知你")
    print()

    # 先测试连接
    balance = test_connections()
    if balance <= 0:
        print("\n  连接失败，无法启动。请先修复上面的问题。")
        return

    print(f"\n  确认信息:")
    print(f"    账户余额: ${balance:,.2f}")
    print(f"    交易模式: 全自动")
    print(f"    监控币种: 12个")
    print(f"    策略: ZigZag→盒子→突破→trailing")
    print()

    confirm = input("  输入 YES 启动交易: ").strip()
    if confirm != 'YES':
        print("  已取消。")
        return

    print(f"\n  🚀 启动中...\n")

    # 用实际余额启动
    script_dir = os.path.dirname(os.path.abspath(__file__))
    main_py = os.path.join(script_dir, 'main.py')
    trade_balance = min(balance, 500)  # 不超过500
    os.system(
        f"PYTHONPATH={os.path.dirname(script_dir)} "
        f"{sys.executable} {main_py} --auto-trade "
        f"--balance {trade_balance:.0f} --db langlang_live.db"
    )


if __name__ == "__main__":
    main()
