#!/usr/bin/env python3
"""
诊断数据加载问题：检查510300.SSE数据是否正确加载
"""

import sys
import types

# 兼容性模块
print("🔧 [DIAG] 加载vnpy.app兼容性模块...")
vnpy_app_module = types.ModuleType('vnpy.app')
sys.modules['vnpy.app'] = vnpy_app_module
submodules = ['cta_strategy', 'cta_backtester', 'data_manager']
for name in submodules:
    full_name = f'vnpy.app.{name}'
    submodule = types.ModuleType(full_name)
    sys.modules[full_name] = submodule
    setattr(vnpy_app_module, name, submodule)

from vnpy_ctastrategy import CtaTemplate, CtaStrategyApp
from vnpy_ctastrategy import (
    CtaTemplate,
    StopOrder,
    TickData,
    BarData,
    TradeData,
    OrderData,
    BarGenerator,
    ArrayManager,
)
from vnpy.trader.constant import Direction, Offset, Interval

sys.modules['vnpy.app.cta_strategy'].CtaTemplate = CtaTemplate
sys.modules['vnpy.app.cta_strategy'].CtaStrategyApp = CtaStrategyApp
vnpy_app_module.CtaTemplate = CtaTemplate
vnpy_app_module.CtaStrategyApp = CtaStrategyApp

from vnpy_ctabacktester import BacktesterEngine
sys.modules['vnpy.app.cta_backtester'].BacktesterEngine = BacktesterEngine
vnpy_app_module.BacktesterEngine = BacktesterEngine

print("✅ [DIAG] vnpy.app兼容性模块加载完成！")

from vnpy.event import EventEngine
from vnpy.trader.engine import MainEngine
from vnpy.trader.database import get_database
from datetime import datetime
import traceback

def str_to_interval(interval_str: str):
    """字符串转Interval枚举"""
    mapping = {
        "1m": Interval.MINUTE,
        "min": Interval.MINUTE,
        "hour": Interval.HOUR,
        "1h": Interval.HOUR,
        "d": Interval.DAILY,
        "1d": Interval.DAILY,
        "daily": Interval.DAILY,
        "w": Interval.WEEKLY,
        "1w": Interval.WEEKLY,
        "weekly": Interval.WEEKLY,
    }
    return mapping.get(interval_str.lower(), Interval.DAILY)

def parse_date(date_val):
    """解析日期"""
    print(f"🔍 [DIAG] 解析日期: date_val = {date_val}, type = {type(date_val)}")
    
    date_ts = float(date_val)
    date_int = int(date_ts)
    s = str(date_int)
    
    print(f"🔍 [DIAG] 处理: date_int = {date_int}, str = '{s}', length = {len(s)}")
    
    if len(s) == 8:
        year = int(s[:4])
        month = int(s[4:6])
        day = int(s[6:8])
        dt = datetime(year, month, day)
        print(f"✅ [DIAG] YYYYMMDD解析: {dt}")
        return dt
    elif len(s) >= 10:
        dt = datetime.fromtimestamp(date_int)
        print(f"✅ [DIAG] Unix时间戳解析: {dt}")
        return dt
    else:
        year = int(s[:4])
        month = int(s[4:6])
        day = int(s[6:8])
        dt = datetime(year, month, day)
        print(f"⚠️ [DIAG] 默认YYYYMMDD解析: {dt}")
        return dt

if __name__ == '__main__':
    print("\n=== 开始诊断数据加载问题 ===")
    
    # 1. 测试日期解析
    print("\n📅 [DIAG] 测试日期解析:")
    start_ts = 1609459200
    end_ts = 1772515200
    
    start_dt = parse_date(start_ts)
    end_dt = parse_date(end_ts)
    
    print(f"\n📅 [DIAG] 日期解析结果:")
    print(f"   start: {start_ts} -> {start_dt}")
    print(f"   end: {end_ts} -> {end_dt}")
    
    # 2. 测试数据库连接
    print("\n💾 [DIAG] 测试数据库连接:")
    db = get_database()
    print(f"✅ [DIAG] 获取数据库成功: {type(db)}")
    
    # 3. 查询bar数据
    symbol = "510300.SSE"
    interval = str_to_interval("1d")
    
    print(f"\n🔍 [DIAG] 查询bar数据: {symbol}, {interval}")
    bars = db.load_bar_data(symbol, interval, start_dt, end_dt)
    
    print(f"✅ [DIAG] 查询完成:")
    print(f"   标的: {symbol}")
    print(f"   时间范围: {start_dt} ~ {end_dt}")
    print(f"   查询到bar数量: {len(bars)}")
    
    if len(bars) > 0:
        print(f"   第一条: {bars[0].datetime}, close={bars[0].close_price}")
        print(f"   最后一条: {bars[-1].datetime}, close={bars[-1].close_price}")
        print(f"   间隔: {bars[0].interval}")
    else:
        print(f"❌ [DIAG] 没有查询到任何bar数据！")
        
        # 尝试查找所有标的
        print(f"\n🔍 [DIAG] 尝试查找所有标的:")
        symbols = db.get_all_symbols()
        print(f"数据库中有 {len(symbols)} 个标的:")
        for s in list(symbols)[:20]:
            print(f"   {s}")
    
    print("\n=== 诊断完成 ===")
