"""
简单的图表生成测试（不依赖其他模块）
"""
import json
from typing import List, Dict, Any

def generate_chart_config(data: List[Dict[str, Any]], chart_type: str, title: str = "数据图表") -> Dict:
    """
    根据数据生成ECharts图表配置
    """
    print(f"[DEBUG] generate_chart_config 被调用: chart_type={chart_type}, title={title}, data_len={len(data) if data else 0}")
    
    if not data or len(data) == 0:
        print(f"[ERROR] 数据为空，无法生成图表")
        return None
    
    # 获取数据的键
    keys = list(data[0].keys())
    print(f"[DEBUG] 数据列: {keys}")
    print(f"[DEBUG] 第一行数据: {data[0]}")
    
    # 尝试识别x轴和y轴数据
    x_key = keys[0]
    y_keys = [k for k in keys[1:] if isinstance(data[0].get(k), (int, float))]
    
    if not y_keys:
        y_keys = [keys[1]] if len(keys) > 1 else []
    
    print(f"[DEBUG] x_key={x_key}, y_keys={y_keys}")
    
    # 提取数据
    x_data = [str(row[x_key]) for row in data]
    
    # 根据图表类型生成配置
    if chart_type == "bar":
        series = []
        for y_key in y_keys:
            y_data = [row[y_key] for row in data]
            series.append({
                "name": y_key,
                "type": "bar",
                "data": y_data
            })
        
        config = {
            "title": {"text": title, "left": "center"},
            "tooltip": {"trigger": "axis", "axisPointer": {"type": "shadow"}},
            "legend": {"data": y_keys, "top": "bottom"},
            "xAxis": {"type": "category", "data": x_data},
            "yAxis": {"type": "value"},
            "series": series
        }
    else:
        config = {"title": {"text": title}}
    
    print(f"[DEBUG] 图表配置生成完成: type={chart_type}, series_count={len(config.get('series', []))}")
    return config

def test_basic():
    """基础测试"""
    print("=" * 60)
    print("测试: 基础柱状图生成")
    print("=" * 60)
    
    test_data = [
        {"sender_id": 1, "message_count": 10},
        {"sender_id": 2, "message_count": 15},
        {"sender_id": 3, "message_count": 8},
    ]
    
    config = generate_chart_config(test_data, "bar", "用户消息统计")
    
    if config:
        print("\n✅ 配置生成成功！")
        print(f"\n配置内容:")
        print(json.dumps(config, indent=2, ensure_ascii=False))
        
        # 验证关键字段
        assert "title" in config, "缺少title"
        assert "series" in config, "缺少series"
        assert len(config["series"]) > 0, "series为空"
        assert "xAxis" in config, "缺少xAxis"
        assert "yAxis" in config, "缺少yAxis"
        
        print("\n✅ 所有验证通过！")
        return True
    else:
        print("\n❌ 配置生成失败")
        return False

if __name__ == "__main__":
    success = test_basic()
    exit(0 if success else 1)
