#!/usr/bin/env python3
"""
浪浪AI 实盘启动向导

$500小资金全自动交易 — 分步启动
按顺序执行每一步，跳过任何一步都有风险。

用法:
    python launch.py step1    # 回测验证
    python launch.py step2    # Telegram设置
    python launch.py step3    # Binance API测试
    python launch.py step4    # 测试网试跑
    python launch.py step5    # 实盘启动
    python launch.py status   # 查看当前状态
"""

import os
import sys
import json
import time

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


def print_header(step, title):
    print(f"\n{'='*60}")
    print(f"  Step {step}: {title}")
    print(f"{'='*60}\n")


def step1_backtest():
    """
    Step 1: 用这套代码跑回测，确认信号一致
    """
    print_header(1, "回测验证")

    print("检查历史数据...")
    from langlang_ai.data.binance_downloader import DATA_DIR
    import glob

    csv_files = glob.glob(os.path.join(DATA_DIR, "*_1h.csv"))
    if not csv_files:
        # 也检查当前目录
        csv_files = glob.glob("*_1h.csv") + glob.glob("historical_data/*_1h.csv")

    if csv_files:
        print(f"  找到 {len(csv_files)} 个数据文件:")
        for f in csv_files:
            print(f"    {os.path.basename(f)}")
        print()
    else:
        print("  未找到历史数据文件。")
        print()
        print("  你有两个选择:")
        print("  A) 如果你之前下载的K线CSV文件在其他位置，")
        print("     把它们放到 historical_data/ 目录下，")
        print("     文件名格式: BTCUSDT_1h.csv, ETHUSDT_1h.csv ...")
        print()
        print("  B) 重新从Binance下载（需要能访问Binance API）:")
        print("     python run_backtest.py --download")
        print()
        print("  C) 用模拟数据先跑一遍验证代码能正常工作:")
        print("     python run_backtest.py --sim --verbose")
        print()

        choice = input("选择 A/B/C (或按回车跳过): ").strip().upper()
        if choice == 'C':
            print("\n运行模拟数据回测...\n")
            os.system(f"{sys.executable} run_backtest.py --sim --verbose")
            return
        elif choice == 'B':
            print("\n下载数据并回测...\n")
            os.system(f"{sys.executable} run_backtest.py --download --verbose")
            return
        elif choice == 'A':
            data_dir = input("请输入K线CSV文件所在目录路径: ").strip()
            if data_dir and os.path.isdir(data_dir):
                os.makedirs(DATA_DIR, exist_ok=True)
                import shutil
                for f in glob.glob(os.path.join(data_dir, "*.csv")):
                    shutil.copy2(f, DATA_DIR)
                    print(f"  复制: {os.path.basename(f)}")
            else:
                print("  路径无效")
                return
        else:
            return

    # 运行回测
    print("\n运行回测...\n")
    os.system(f"{sys.executable} run_backtest.py --verbose")

    print("\n" + "="*60)
    print("  回测完成！请检查以上结果：")
    print("  - 交易数量是否接近437笔？")
    print("  - PF是否接近8.14？")
    print("  - 如果差距大，先不要上实盘")
    print("="*60)


def step2_telegram():
    """
    Step 2: 设置Telegram通知
    """
    print_header(2, "Telegram通知设置")

    print("  Telegram通知不是必须的，但强烈建议设置。")
    print("  这样你能实时知道系统开了什么仓、平了什么仓。")
    print()

    skip = input("  要设置Telegram吗？(Y/n): ").strip().lower()
    if skip == 'n':
        print("  跳过Telegram设置。系统会正常运行，只是不发通知。")
        return

    print()
    print("  第1步: 打开Telegram，搜索 @BotFather")
    print("  第2步: 发送 /newbot，按提示取个名字")
    print("  第3步: BotFather会给你一个Token，长这样:")
    print("         123456789:ABCdefGHIjklMNOpqrsTUVwxyz")
    print()

    token = input("  粘贴你的Bot Token: ").strip()

    print()
    print("  第4步: 打开Telegram，搜索 @userinfobot")
    print("  第5步: 给它发任意消息，它会回复你的Chat ID")
    print("         Chat ID是一串数字，如: 987654321")
    print()

    chat_id = input("  粘贴你的Chat ID: ").strip()

    if token and chat_id:
        # 测试发送
        print("\n  测试发送消息...")
        from langlang_ai.notify.telegram_bot import TelegramNotifier
        notifier = TelegramNotifier(token, chat_id)
        ok = notifier.send_sync("🚀 浪浪AI 测试消息 — Telegram连接成功！")

        if ok:
            print("  ✓ 消息发送成功！检查你的Telegram。")
        else:
            print("  ✗ 发送失败，请检查Token和Chat ID是否正确。")
            return

        # 保存到环境变量提示
        print()
        print("  保存配置（添加到你的shell配置文件）:")
        print(f'  export TELEGRAM_BOT_TOKEN="{token}"')
        print(f'  export TELEGRAM_CHAT_ID="{chat_id}"')

        # 也保存到本地配置文件
        config = {'TELEGRAM_BOT_TOKEN': token, 'TELEGRAM_CHAT_ID': chat_id}
        config_path = os.path.join(os.path.dirname(__file__), '.env')
        existing = {}
        if os.path.exists(config_path):
            with open(config_path) as f:
                for line in f:
                    if '=' in line:
                        k, v = line.strip().split('=', 1)
                        existing[k] = v
        existing.update(config)
        with open(config_path, 'w') as f:
            for k, v in existing.items():
                f.write(f"{k}={v}\n")
        print(f"\n  ✓ 已保存到 {config_path}")
    else:
        print("  Token或Chat ID为空，跳过。")


def step3_binance():
    """
    Step 3: 配置并测试Binance API
    """
    print_header(3, "Binance API配置")

    print("  在Binance创建API Key:")
    print("  1. 登录 binance.com → API管理 → 创建API")
    print("  2. 勾选: ✅ 启用合约交易")
    print("  3. 不勾选: ❌ 启用提现（重要！）")
    print("  4. IP限制: 建议绑定你电脑/VPS的IP")
    print()

    api_key = input("  API Key: ").strip()
    api_secret = input("  API Secret: ").strip()

    if not api_key or not api_secret:
        print("  API信息为空，跳过。")
        return

    # 测试连接
    print("\n  测试API连接...")
    try:
        from langlang_ai.execution.binance_client import BinanceClient

        client = BinanceClient(api_key, api_secret)
        balance = client.get_balance()
        positions = client.get_positions()

        print(f"  ✓ 连接成功!")
        print(f"    USDT余额: ${balance:,.2f}")
        print(f"    活跃持仓: {len(positions)}个")

        if balance < 100:
            print(f"\n  ⚠️ 余额只有${balance:.2f}，建议至少$500")

        # 保存
        config_path = os.path.join(os.path.dirname(__file__), '.env')
        existing = {}
        if os.path.exists(config_path):
            with open(config_path) as f:
                for line in f:
                    if '=' in line:
                        k, v = line.strip().split('=', 1)
                        existing[k] = v

        existing['BINANCE_API_KEY'] = api_key
        existing['BINANCE_API_SECRET'] = api_secret

        with open(config_path, 'w') as f:
            for k, v in existing.items():
                f.write(f"{k}={v}\n")
        print(f"\n  ✓ 已保存到 {config_path}")

    except Exception as e:
        print(f"  ✗ 连接失败: {e}")
        print("    检查API Key是否正确，以及是否开通了合约交易权限")


def step4_testnet():
    """
    Step 4: 测试网试跑
    """
    print_header(4, "测试网试跑")

    print("  Binance Futures测试网:")
    print("  https://testnet.binancefuture.com")
    print()
    print("  1. 用你的Binance账号登录测试网")
    print("  2. 在测试网创建API Key")
    print("  3. 测试网有免费的测试资金")
    print()
    print("  或者跳过测试网，直接用$500实盘（风险自担）")
    print()

    skip = input("  要跑测试网吗？(Y/n): ").strip().lower()
    if skip == 'n':
        print("  跳过测试网。")
        return

    testnet_key = input("  测试网 API Key: ").strip()
    testnet_secret = input("  测试网 API Secret: ").strip()

    if testnet_key and testnet_secret:
        print("\n  启动测试网监控（Ctrl+C停止）...")
        os.environ['BINANCE_API_KEY'] = testnet_key
        os.environ['BINANCE_API_SECRET'] = testnet_secret

        # 加载Telegram配置
        _load_env()

        os.system(
            f"{sys.executable} main.py --auto-trade --testnet "
            f"--balance 500 --once"
        )
    else:
        print("  API信息为空，跳过。")


def step5_live():
    """
    Step 5: $500实盘启动
    """
    print_header(5, "$500 实盘全自动交易")

    print("  ⚠️  重要提醒:")
    print("  - 这是真金白银，亏损不可逆")
    print("  - 确保你已完成Step 1-3")
    print("  - 止损会自动挂单保护你的仓位")
    print("  - 日亏>5%会自动暂停，回撤>25%会全部平仓")
    print()

    # 加载配置
    _load_env()

    api_key = os.environ.get('BINANCE_API_KEY', '')
    api_secret = os.environ.get('BINANCE_API_SECRET', '')

    if not api_key or not api_secret:
        print("  ✗ 未找到Binance API配置")
        print("    请先运行: python launch.py step3")
        return

    # 最终确认
    print("  当前配置:")
    print(f"    API Key: {api_key[:8]}...{api_key[-4:]}")
    print(f"    Telegram: {'已配置' if os.environ.get('TELEGRAM_BOT_TOKEN') else '未配置'}")
    print(f"    资金: $500")
    print(f"    模式: 全自动交易（实盘）")
    print()

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

    print("\n  🚀 启动全自动交易...")
    print("  按 Ctrl+C 停止\n")

    # 先初始化数据（如果是第一次）
    from langlang_ai.data.database import Database
    db = Database('langlang_live.db')
    count = db.get_kline_count('BTCUSDT', '1h')
    db.close()

    if count < 1000:
        print("  首次运行，初始化历史数据...")
        os.system(
            f"{sys.executable} main.py --auto-trade "
            f"--balance 500 --db langlang_live.db --init --once"
        )
        print("  数据初始化完成，启动持续监控...\n")

    os.system(
        f"{sys.executable} main.py --auto-trade "
        f"--balance 500 --db langlang_live.db"
    )


def show_status():
    """查看当前状态"""
    print_header("?", "系统状态")

    # 检查配置
    _load_env()

    checks = {
        'Binance API': bool(os.environ.get('BINANCE_API_KEY')),
        'Telegram Bot': bool(os.environ.get('TELEGRAM_BOT_TOKEN')),
        '历史数据': os.path.exists('historical_data') and len(os.listdir('historical_data')) > 0 if os.path.exists('historical_data') else False,
        '数据库': os.path.exists('langlang_live.db'),
    }

    for name, ok in checks.items():
        print(f"  {'✓' if ok else '✗'} {name}")

    # 检查数据库状态
    if os.path.exists('langlang_live.db'):
        from langlang_ai.data.database import Database
        db = Database('langlang_live.db')
        btc_count = db.get_kline_count('BTCUSDT', '1h')
        balance = db.get_state('balance', 'N/A')
        consec = db.get_state('consecutive_losses', '0')
        halted = db.get_state('risk_halted', '0')
        db.close()

        print(f"\n  数据库状态:")
        print(f"    BTC K线: {btc_count}根")
        print(f"    余额: ${balance}")
        print(f"    连败: {consec}笔")
        print(f"    熔断: {'是' if halted=='1' else '否'}")

    print()
    print("  下一步:")
    if not checks['Binance API']:
        print("    → python launch.py step3  (配置API)")
    elif not checks.get('历史数据') and not checks['数据库']:
        print("    → python launch.py step1  (回测验证)")
    else:
        print("    → python launch.py step5  (启动实盘)")


def _load_env():
    """从.env文件加载环境变量"""
    env_path = os.path.join(os.path.dirname(__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.setdefault(k.strip(), v.strip())


def main():
    if len(sys.argv) < 2:
        print("浪浪AI 实盘启动向导")
        print()
        print("用法:")
        print("  python launch.py step1    回测验证")
        print("  python launch.py step2    Telegram设置")
        print("  python launch.py step3    Binance API配置")
        print("  python launch.py step4    测试网试跑")
        print("  python launch.py step5    $500实盘启动")
        print("  python launch.py status   查看状态")
        print()
        print("按顺序执行 step1 → step5")
        return

    cmd = sys.argv[1].lower()

    if cmd == 'step1':
        step1_backtest()
    elif cmd == 'step2':
        step2_telegram()
    elif cmd == 'step3':
        step3_binance()
    elif cmd == 'step4':
        step4_testnet()
    elif cmd == 'step5':
        step5_live()
    elif cmd == 'status':
        show_status()
    else:
        print(f"未知命令: {cmd}")
        print("可用: step1 step2 step3 step4 step5 status")


if __name__ == "__main__":
    main()
