"""
测试图表生成功能
"""
import sys
import json
sys.path.append('.')

from api.chat_assistant import generate_chart_config

def test_bar_chart():
    """测试柱状图"""
    print("=" * 60)
    print("测试1: 柱状图")
    print("=" * 60)
    
    test_data = [
        {"sender_id": 1, "message_count": 10},
        {"sender_id": 2, "message_count": 15},
        {"sender_id": 3, "message_count": 8},
        {"sender_id": 4, "message_count": 20},
    ]
    
    config = generate_chart_config(test_data, "bar", "用户消息统计")
    
    if config:
        print("✅ 柱状图配置生成成功")
        print(f"   - 标题: {config['title']['text']}")
        print(f"   - 系列数: {len(config['series'])}")
        print(f"   - X轴数据: {config['xAxis']['data']}")
        print(f"   - Y轴数据: {config['series'][0]['data']}")
    else:
        print("❌ 柱状图配置生成失败")
    
    return config is not None

def test_line_chart():
    """测试折线图"""
    print("\n" + "=" * 60)
    print("测试2: 折线图")
    print("=" * 60)
    
    test_data = [
        {"date": "2024-04-15", "count": 10},
        {"date": "2024-04-16", "count": 15},
        {"date": "2024-04-17", "count": 12},
        {"date": "2024-04-18", "count": 18},
    ]
    
    config = generate_chart_config(test_data, "line", "每日消息趋势")
    
    if config:
        print("✅ 折线图配置生成成功")
        print(f"   - 标题: {config['title']['text']}")
        print(f"   - 系列数: {len(config['series'])}")
        print(f"   - X轴数据: {config['xAxis']['data']}")
    else:
        print("❌ 折线图配置生成失败")
    
    return config is not None

def test_pie_chart():
    """测试饼图"""
    print("\n" + "=" * 60)
    print("测试3: 饼图")
    print("=" * 60)
    
    test_data = [
        {"message_type": "text", "count": 100},
        {"message_type": "emoji", "count": 30},
        {"message_type": "image", "count": 20},
    ]
    
    config = generate_chart_config(test_data, "pie", "消息类型分布")
    
    if config:
        print("✅ 饼图配置生成成功")
        print(f"   - 标题: {config['title']['text']}")
        print(f"   - 数据项数: {len(config['series'][0]['data'])}")
        for item in config['series'][0]['data']:
            print(f"   - {item['name']}: {item['value']}")
    else:
        print("❌ 饼图配置生成失败")
    
    return config is not None

def test_empty_data():
    """测试空数据"""
    print("\n" + "=" * 60)
    print("测试4: 空数据处理")
    print("=" * 60)
    
    config = generate_chart_config([], "bar", "空数据测试")
    
    if config is None:
        print("✅ 空数据正确返回None")
    else:
        print("❌ 空数据应该返回None")
    
    return config is None

def test_string_numbers():
    """测试字符串数字"""
    print("\n" + "=" * 60)
    print("测试5: 字符串数字处理")
    print("=" * 60)
    
    test_data = [
        {"user": "Alice", "count": "10"},  # count是字符串
        {"user": "Bob", "count": "15"},
        {"user": "Charlie", "count": "8"},
    ]
    
    config = generate_chart_config(test_data, "bar", "字符串数字测试")
    
    if config:
        print("⚠️  字符串数字生成了配置（可能不正确）")
        print(f"   - Y轴键: {config['legend']['data']}")
        # 字符串数字不会被识别为数值列，会使用第二列
    else:
        print("❌ 字符串数字配置生成失败")
    
    return True  # 这个测试主要是观察行为

def test_real_query_result():
    """测试真实查询结果格式"""
    print("\n" + "=" * 60)
    print("测试6: 真实查询结果格式")
    print("=" * 60)
    
    # 模拟真实的SQL查询结果
    test_data = [
        {"sender_id": 1, "message_count": 10},
        {"sender_id": 2, "message_count": 15},
        {"sender_id": 3, "message_count": 8},
    ]
    
    # 测试完整的JSON序列化
    try:
        json_str = json.dumps({"type": "chart_result", "success": True, "config": generate_chart_config(test_data, "bar", "测试")}, ensure_ascii=False)
        print(f"✅ JSON序列化成功，长度: {len(json_str)} 字符")
    except Exception as e:
        print(f"❌ JSON序列化失败: {e}")
        return False
    
    return True

def main():
    """运行所有测试"""
    print("\n" + "=" * 60)
    print("图表生成功能测试")
    print("=" * 60)
    
    results = []
    
    results.append(("柱状图", test_bar_chart()))
    results.append(("折线图", test_line_chart()))
    results.append(("饼图", test_pie_chart()))
    results.append(("空数据", test_empty_data()))
    results.append(("字符串数字", test_string_numbers()))
    results.append(("JSON序列化", test_real_query_result()))
    
    print("\n" + "=" * 60)
    print("测试总结")
    print("=" * 60)
    
    passed = sum(1 for _, result in results if result)
    total = len(results)
    
    for name, result in results:
        status = "✅ 通过" if result else "❌ 失败"
        print(f"{status} - {name}")
    
    print(f"\n总计: {passed}/{total} 测试通过")
    
    if passed == total:
        print("\n🎉 所有测试通过！图表生成功能正常。")
    else:
        print(f"\n⚠️  有 {total - passed} 个测试失败，请检查。")

if __name__ == "__main__":
    main()
