import pandas as pd
import numpy as np
import asyncio

# 导入所需模块
import sys
import os

# 添加MFM目录到路径
current_dir = os.path.dirname(os.path.abspath(__file__))
# py_tools -> route -> FFEv3_2 -> FFE -> MFM -> 根目录
root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(current_dir)))))
if root_dir not in sys.path:
    sys.path.append(root_dir)

from myffe.tools.interactive import interactive
from myffe.tools.color_printer import ColorPrinter
from myffe.tools.visualize_route import visualize_route
from myffe.tools.interactive_utils import get_interactive_choice
from myffe.route.tools_py.time_detector import detect_time_columns, batch_analyze_time_columns



def analyze_time_distribution(data, auto_test=False):
    """分析数据的时间分布，推荐适合的时间处理方法
    
    Args:
        data: pandas DataFrame，输入数据
        auto_test: bool，是否自动测试模式，默认为 False
    
    Returns:
        dict: 包含时间处理参数的字典
    """
    # 初始化处理路线
    time_route = {}
    
    # 展示数据前5行
    ColorPrinter.print_info("=" * 60)
    ColorPrinter.print_info("数据前5行：")
    ColorPrinter.print_info("=" * 60)
    ColorPrinter.print_any(data.head(), color='white')
    ColorPrinter.print_any("", color='white')
    
    # 询问是否使用智能推荐
    inter_time = get_interactive_choice(
        title="是否使用智能推荐？",
        description="选择'ok'将自动检测时间列并设置处理方法，选择'no'需要手动选择",
        auto_test=auto_test
    )
    
    # 找出时间列
    time_columns = asyncio.run(detect_time_columns(data))
    
    # 构建时间处理参数
    time_preprocessing_params = {
        'time_ways': []  # 存储每个时间列的处理参数
    }
    
    if inter_time:
        # 智能推荐模式
        if time_columns:
            ColorPrinter.print_success(f"智能推荐时间列：{time_columns}")
            
            # 批量分析时间列
            analysis_results = asyncio.run(batch_analyze_time_columns(data, time_columns))
            
            # 为每个时间列生成处理参数
            for result in analysis_results:
                col = result['column']
                time_type = result['recommended_type']
                
                if result['has_time_info']:
                    ColorPrinter.print_success(f"智能推荐 {col} 处理类型：{time_type}（高级，包含时间信息）")
                else:
                    ColorPrinter.print_success(f"智能推荐 {col} 处理类型：{time_type}（基础）")
                
                # 为当前列创建参数配置
                col_params = {
                    'time_col': col,
                    'time_type': time_type
                }
                
                # 添加到time_ways列表
                time_preprocessing_params['time_ways'].append(col_params)
        else:
            ColorPrinter.print_info("智能推荐：未检测到时间列")
    else:
        # 手动选择模式
        all_cols = list(data.columns)
        ColorPrinter.print_info("请选择时间列（按'm'键多选，按回车键确认）")
        selected_cols = interactive(all_cols, title="请按上下箭头选择，回车确认时间列,点击'm'键进行多选择", description="选择作为时间索引的列", min_select=1, max_select=len(all_cols)).run()
        
            # 为每个选择的时间列单独设置处理类型
        for col in selected_cols:
            # 手动选择时间处理类型
            time_type_choice = interactive(['basic', 'advance'], title=f"请选择 {col} 的处理类型", description="basic: 基础时间特征, advance: 高级时间特征", min_select=1, max_select=1).run()
            time_type = time_type_choice[0] if time_type_choice else 'basic'
            ColorPrinter.print_success(f"选择 {col} 处理类型：{time_type}")
            
            # 为当前列创建参数配置
            col_params = {
                'time_col': col,
                'time_type': time_type
            }
            
            # 添加到time_ways列表
            time_preprocessing_params['time_ways'].append(col_params)
    
    # 智能推荐模式下未检测到时间列的情况
    if not time_columns and inter_time:
        ColorPrinter.print_info("智能推荐：未检测到时间列")
        return {'time_preprocessing': 'skip'}
    
    time_route['time_preprocessing'] = time_preprocessing_params
    
    visualize_route(time_route)
    return time_route

def time_py(data, auto_test=False):
    """Python实现的时间处理分析
    
    Args:
        data: pandas DataFrame，输入数据
        auto_test: bool，是否自动测试模式，默认为 False
    
    Returns:
        dict: 包含时间处理参数的字典
    """
    
    return analyze_time_distribution(data, auto_test=auto_test)

if __name__ == "__main__":
    # 测试代码
    import pandas as pd
    import numpy as np
    
    print("=" * 80)
    print("time_py 模块测试")
    print("=" * 80)
    
    # 测试场景1: 标准日期格式
    print(f"\n{'=' * 60}")
    print("测试场景1: 标准日期格式")
    print('=' * 60)
    
    np.random.seed(42)
    data1 = pd.DataFrame({
        'date': pd.date_range('2023-01-01', periods=20),
        'numeric_col1': np.random.normal(100, 10, 20),
        'numeric_col2': np.random.normal(50, 5, 20),
        'categorical_col': np.random.choice(['A', 'B', 'C'], 20)
    })
    
    ColorPrinter.print_info("测试数据:")
    ColorPrinter.print_any(data1.head(), color='white')
    ColorPrinter.print_any("\n数据类型:", color='blue')
    ColorPrinter.print_any(data1.dtypes, color='white')
    
    ColorPrinter.print_info("\n测试时间处理:")
    result1 = time_py(data1, auto_test=True)
    ColorPrinter.print_success("处理结果:")
    ColorPrinter.print_any(result1, color='white')
    
    # 验证结果结构
    if result1 != 'skip':
        assert 'time_preprocessing' in result1, "结果应包含 time_preprocessing 键"
        assert 'time_ways' in result1['time_preprocessing'], "结果应包含 time_ways 列表"
        assert len(result1['time_preprocessing']['time_ways']) > 0, "time_ways 列表不应为空"
        ColorPrinter.print_success("测试场景1 验证通过！")
    else:
        ColorPrinter.print_info("测试场景1: 未检测到时间列")
    
    # 测试场景2: 多时间列
    print(f"\n{'=' * 60}")
    print("测试场景2: 多时间列")
    print('=' * 60)
    
    data2 = pd.DataFrame({
        'date': pd.date_range('2023-01-01', periods=20),
        'time_stamp': pd.date_range('2023-01-01', periods=20, freq='h'),
        'numeric_col': np.random.normal(100, 10, 20),
        'label': np.random.choice(['A', 'B'], 20)
    })
    
    ColorPrinter.print_info("测试数据:")
    ColorPrinter.print_any(data2.head(), color='white')
    ColorPrinter.print_any("\n数据类型:", color='blue')
    ColorPrinter.print_any(data2.dtypes, color='white')
    
    ColorPrinter.print_info("\n测试时间处理:")
    result2 = time_py(data2, auto_test=True)
    ColorPrinter.print_success("处理结果:")
    ColorPrinter.print_any(result2, color='white')
    
    # 验证结果结构
    if result2 != 'skip':
        assert 'time_preprocessing' in result2, "结果应包含 time_preprocessing 键"
        assert 'time_ways' in result2['time_preprocessing'], "结果应包含 time_ways 列表"
        assert len(result2['time_preprocessing']['time_ways']) >= 2, "应检测到至少两个时间列"
        ColorPrinter.print_success("测试场景2 验证通过！")
    else:
        ColorPrinter.print_info("测试场景2: 未检测到时间列")
    
    # 测试场景3: 字符串时间格式
    print(f"\n{'=' * 60}")
    print("测试场景3: 字符串时间格式")
    print('=' * 60)
    
    data3 = pd.DataFrame({
        'date_str': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05'],
        'numeric_col': np.random.randint(1, 100, 5),
        'label': ['A', 'B', 'A', 'B', 'A']
    })
    
    ColorPrinter.print_info("测试数据:")
    ColorPrinter.print_any(data3.head(), color='white')
    ColorPrinter.print_any("\n数据类型:", color='blue')
    ColorPrinter.print_any(data3.dtypes, color='white')
    
    ColorPrinter.print_info("\n测试时间处理:")
    result3 = time_py(data3, auto_test=True)
    ColorPrinter.print_success("处理结果:")
    ColorPrinter.print_any(result3, color='white')
    
    # 验证结果结构
    if result3 != 'skip':
        assert 'time_preprocessing' in result3, "结果应包含 time_preprocessing 键"
        assert 'time_ways' in result3['time_preprocessing'], "结果应包含 time_ways 列表"
        assert len(result3['time_preprocessing']['time_ways']) > 0, "应检测到时间列"
        ColorPrinter.print_success("测试场景3 验证通过！")
    else:
        ColorPrinter.print_info("测试场景3: 未检测到时间列")
    
    # 测试场景4: 无时间列
    print(f"\n{'=' * 60}")
    print("测试场景4: 无时间列")
    print('=' * 60)
    
    data4 = pd.DataFrame({
        'feature1': np.random.randint(1, 100, 5),
        'feature2': np.random.randint(1, 100, 5),
        'label': ['A', 'B', 'A', 'B', 'A']
    })
    
    ColorPrinter.print_info("测试数据:")
    ColorPrinter.print_any(data4.head(), color='white')
    ColorPrinter.print_any("\n数据类型:", color='blue')
    ColorPrinter.print_any(data4.dtypes, color='white')
    
    ColorPrinter.print_info("\n测试时间处理:")
    result4 = time_py(data4, auto_test=True)
    ColorPrinter.print_success("处理结果:")
    ColorPrinter.print_any(result4, color='white')
    
    # 验证结果结构
    assert result4 == {'time_preprocessing': 'skip'}, "无时间列时应返回 {'time_preprocessing': 'skip'}"
    ColorPrinter.print_success("测试场景4 验证通过！")
    
    # 测试场景5: 不同格式的字符串时间
    print(f"\n{'=' * 60}")
    print("测试场景5: 不同格式的字符串时间")
    print('=' * 60)
    
    data5 = pd.DataFrame({
        'date_format1': ['01-01-2023', '01-02-2023', '01-03-2023', '01-04-2023', '01-05-2023'],
        'date_format2': ['2023/01/01', '2023/01/02', '2023/01/03', '2023/01/04', '2023/01/05'],
        'date_format3': ['2023-01-01 12:00:00', '2023-01-02 13:30:00', '2023-01-03 14:45:00', '2023-01-04 15:00:00', '2023-01-05 16:15:00'],
        'numeric_col': np.random.randint(1, 100, 5)
    })
    
    ColorPrinter.print_info("测试数据:")
    ColorPrinter.print_any(data5.head(), color='white')
    ColorPrinter.print_any("\n数据类型:", color='blue')
    ColorPrinter.print_any(data5.dtypes, color='white')
    
    ColorPrinter.print_info("\n测试时间处理:")
    result5 = time_py(data5, auto_test=True)
    ColorPrinter.print_success("处理结果:")
    ColorPrinter.print_any(result5, color='white')
    
    # 验证结果结构
    if result5 != 'skip':
        assert 'time_preprocessing' in result5, "结果应包含 time_preprocessing 键"
        assert 'time_ways' in result5['time_preprocessing'], "结果应包含 time_ways 列表"
        ColorPrinter.print_success("测试场景5 验证通过！")
    else:
        ColorPrinter.print_info("测试场景5: 未检测到时间列")
    
    # 测试场景6: 空数据框
    print(f"\n{'=' * 60}")
    print("测试场景6: 空数据框")
    print('=' * 60)
    
    data6 = pd.DataFrame()
    
    ColorPrinter.print_info("测试数据:")
    ColorPrinter.print_any(data6.head(), color='white')
    ColorPrinter.print_any("\n数据类型:", color='blue')
    ColorPrinter.print_any(data6.dtypes, color='white')
    
    ColorPrinter.print_info("\n测试时间处理:")
    result6 = time_py(data6, auto_test=True)
    ColorPrinter.print_success("处理结果:")
    ColorPrinter.print_any(result6, color='white')
    
    # 验证结果结构
    assert result6 == {'time_preprocessing': 'skip'}, "空数据框时应返回 {'time_preprocessing': 'skip'}"
    ColorPrinter.print_success("测试场景6 验证通过！")
    
    # 测试场景7: 只有时间列的数据框
    print(f"\n{'=' * 60}")
    print("测试场景7: 只有时间列的数据框")
    print('=' * 60)
    
    data7 = pd.DataFrame({
        'date1': pd.date_range('2023-01-01', periods=10),
        'date2': pd.date_range('2023-01-01', periods=10, freq='h')
    })
    
    ColorPrinter.print_info("测试数据:")
    ColorPrinter.print_any(data7.head(), color='white')
    ColorPrinter.print_any("\n数据类型:", color='blue')
    ColorPrinter.print_any(data7.dtypes, color='white')
    
    ColorPrinter.print_info("\n测试时间处理:")
    result7 = time_py(data7, auto_test=True)
    ColorPrinter.print_success("处理结果:")
    ColorPrinter.print_any(result7, color='white')
    
    # 验证结果结构
    if result7 != 'skip':
        assert 'time_preprocessing' in result7, "结果应包含 time_preprocessing 键"
        assert 'time_ways' in result7['time_preprocessing'], "结果应包含 time_ways 列表"
        assert len(result7['time_preprocessing']['time_ways']) > 0, "应检测到时间列"
        ColorPrinter.print_success("测试场景7 验证通过！")
    else:
        ColorPrinter.print_info("测试场景7: 未检测到时间列")
    
    print("\n" + "=" * 80)
    print("所有测试完成！")
    print("=" * 80)
