#!/usr/bin/env python3
"""OpenClaw Phase 3 功能验证 Demo"""

import asyncio


async def main():
    print('=' * 60)
    print('🦞 OpenClaw Trading - Phase 3 功能验证')
    print('=' * 60)
    print()

    # 1. 验证导入
    print('📦 模块导入测试...')
    from openclaw.backtest.engine import BacktestEngine
    from openclaw.backtest.analyzer import PerformanceAnalyzer
    from openclaw.exchange.base import Exchange
    from openclaw.exchange.mock import MockExchange
    from openclaw.exchange.models import Order, Balance, Position, Ticker
    from openclaw.trading.live_mode import LiveModeManager, LiveModeConfig
    from openclaw.monitoring.system import SystemMonitor
    from openclaw.monitoring.metrics import MetricsCollector
    from openclaw.monitoring.log_analyzer import LogAnalyzer
    print('✅ 所有 Phase 3 模块导入成功！')
    print()

    # 2. 回测引擎
    print('📊 回测引擎...')
    import pandas as pd
    import numpy as np
    from datetime import datetime, timedelta

    # 创建模拟价格数据
    dates = pd.date_range(start='2024-01-01', end='2024-01-30', freq='D')
    prices = 100 + np.cumsum(np.random.randn(len(dates)) * 2)
    price_data = pd.DataFrame({
        'open': prices * 0.99,
        'high': prices * 1.02,
        'low': prices * 0.98,
        'close': prices,
        'volume': np.random.randint(1000, 10000, len(dates))
    }, index=dates)

    engine = BacktestEngine(
        initial_capital=10000.0,
        start_date=datetime(2024, 1, 1),
        end_date=datetime(2024, 1, 30)
    )
    print(f'   初始资金: ${engine.initial_capital:,.2f}')
    print(f'   回测周期: {engine.start_date.date()} ~ {engine.end_date.date()}')
    print()

    # 3. 回测分析器
    print('📈 回测分析器...')
    analyzer = PerformanceAnalyzer()

    # 模拟权益曲线
    equity_curve = pd.Series(
        10000 * (1 + np.cumsum(np.random.randn(30) * 0.01)),
        index=dates
    )

    returns = analyzer.calculate_returns(equity_curve)
    max_dd = analyzer.calculate_max_drawdown(equity_curve)
    sharpe = analyzer.calculate_sharpe_ratio(returns)

    print(f'   总收益率: {returns[-1]:.2%}')
    print(f'   最大回撤: {max_dd["max_drawdown"]:.2%}')
    print(f'   夏普比率: {sharpe:.2f}')
    print()

    # 4. 交易所接口
    print('🏦 交易所接口...')
    exchange = MockExchange(
        initial_balances={'USDT': 10000.0, 'BTC': 0.0}
    )

    # 设置当前价格
    exchange.update_ticker('BTC/USDT', 50050.0)

    # 下单
    order = await exchange.place_order(
        symbol='BTC/USDT',
        side='buy',
        amount=0.1,
        price=50100.0
    )

    balance = await exchange.get_balance()
    print(f'   下单: BUY 0.1 BTC @ $50,100')
    print(f'   当前余额: {[(b.asset, b.free) for b in balance]}')
    print()

    # 5. 实盘模式
    print('🔴 实盘模式...')
    live_config = LiveModeConfig(
        enabled=True,
        daily_trade_limit_usd=1000.0,
        max_position_pct=0.5,
        require_confirmation=True
    )
    live_manager = LiveModeManager(config=live_config)

    print(f'   实盘模式: {live_manager.is_live_mode}')
    print(f'   每日限额: ${live_config.daily_trade_limit_usd:,.2f}')
    print(f'   最大仓位: {live_config.max_position_pct:.0%}')

    # 验证交易
    is_valid, reason = live_manager.validate_live_trade(
        symbol='BTC/USDT',
        amount=0.1,
        price=50000.0,
        current_balance=10000.0
    )
    print(f'   交易验证: {reason}')
    print()

    # 6. 系统监控
    print('📡 系统监控...')
    system_monitor = SystemMonitor()
    metrics = system_monitor.collect_system_metrics()

    print(f'   CPU 使用率: {metrics.cpu_percent:.1f}%')
    print(f'   内存使用: {metrics.memory_percent:.1f}%')
    print(f'   线程数: {metrics.thread_count}')
    print()

    # 7. 指标收集
    print('📊 指标收集...')
    metrics_collector = MetricsCollector()

    counter = metrics_collector.counter('trades_total', 'Total trades')
    counter.inc()
    counter.inc(labels={'symbol': 'BTC/USDT'})

    gauge = metrics_collector.gauge('balance', 'Current balance')
    gauge.set(10500.0, {'agent_id': 'trader-001'})

    print(f'   交易计数: {counter._values}')
    print(f'   余额指标: {gauge._values}')
    print()

    # 8. 日志分析器
    print('📝 日志分析器...')
    log_analyzer = LogAnalyzer()

    # 添加示例日志条目
    from openclaw.monitoring.log_analyzer import LogEntry

    log_analyzer.add_entry(LogEntry(
        timestamp=datetime.now(),
        level='INFO',
        message='Trade executed: BUY 0.1 BTC',
        module='trading',
        function='execute_trade',
        line=42,
        extra={'trade_id': 'T001', 'agent_id': 'trader-001'}
    ))

    log_analyzer.add_entry(LogEntry(
        timestamp=datetime.now(),
        level='ERROR',
        message='Failed to connect to exchange',
        module='exchange',
        function='connect',
        line=25
    ))

    # 分析
    info_logs = log_analyzer.filter_by_level('INFO')
    agent_logs = log_analyzer.filter_by_agent('trader-001')
    error_stats = log_analyzer.get_error_stats()

    print(f'   总日志数: {log_analyzer.entry_count}')
    print(f'   INFO级别: {len(info_logs)}')
    print(f'   Agent日志: {len(agent_logs)}')
    print(f'   错误数: {error_stats["total_errors"]}')
    print()

    print('=' * 60)
    print('✅ Phase 3 所有功能验证通过！')
    print('=' * 60)
    print()
    print('Phase 3 实现的功能:')
    print('  - 回测引擎 (BacktestEngine)')
    print('  - 回测分析器 (PerformanceAnalyzer)')
    print('  - 交易所接口 (Exchange, MockExchange)')
    print('  - 实盘模式 (LiveModeManager)')
    print('  - 系统监控 (SystemMonitor)')
    print('  - 指标收集 (MetricsCollector)')
    print('  - 日志分析 (LogAnalyzer)')


if __name__ == '__main__':
    asyncio.run(main())
