"""
数据洞察组件的工具函数模块
用于支持数据分析和可视化功能
"""
import json
import pandas as pd
import streamlit as st
import plotly.express as px
import numpy as np

from super_datascope.components.json_path_extractor import JsonColumnAnalyzer
from super_datascope.components.data_paginator import InteractiveDataSelector
from super_datascope.components.sql_generator import DataAnalysisSqlGenerator

def analyze_column_data_type(sample_data):
    """分析列数据类型并返回详细信息"""
    if sample_data.empty:
        return {"type": "empty", "description": "无数据", "is_list": False, "is_json": False}
    
    first_value = sample_data.iloc[0]
    
    # 检测numpy数组类型（通常来自SQL查询结果）
    if isinstance(first_value, np.ndarray):
        try:
            list_value = first_value.tolist()
            if isinstance(list_value, list):
                if len(list_value) == 0:
                    return {"type": "empty_list", "description": "空列表 (numpy数组)", "is_list": True, "is_json": False}
                
                # 分析列表元素类型
                element_type = type(list_value[0]).__name__
                element_types = set(type(x).__name__ for x in list_value[:5])
                
                if len(element_types) == 1:
                    if element_type == "str":
                        return {"type": "list_str", "description": f"字符串列表 (numpy数组: {list_value[:3]})", "is_list": True, "is_json": False}
                    elif element_type in ["int", "float"]:
                        return {"type": "list_num", "description": f"数值列表 (numpy数组: {list_value[:3]})", "is_list": True, "is_json": False}
                    elif element_type == "dict":
                        return {"type": "list_dict", "description": "字典列表 (numpy数组)", "is_list": True, "is_json": True}
                else:
                    return {"type": "list_mixed", "description": f"混合类型列表 (numpy数组: {', '.join(element_types)})", "is_list": True, "is_json": False}
            else:
                # 单个标量值的numpy数组
                return {"type": "numpy_scalar", "description": f"numpy标量 ({type(list_value).__name__})", "is_list": False, "is_json": False}
        except:
            return {"type": "numpy_array", "description": f"numpy数组 (shape: {first_value.shape})", "is_list": False, "is_json": False}
    
    # 检测列表类型
    elif isinstance(first_value, list):
        if len(first_value) == 0:
            return {"type": "empty_list", "description": "空列表", "is_list": True, "is_json": False}
        
        # 分析列表元素类型
        element_type = type(first_value[0]).__name__
        element_types = set(type(x).__name__ for x in first_value[:5])
        
        if len(element_types) == 1:
            if element_type == "str":
                return {"type": "list_str", "description": f"字符串列表 (示例: {first_value[:3]})", "is_list": True, "is_json": False}
            elif element_type in ["int", "float"]:
                return {"type": "list_num", "description": f"数值列表 (示例: {first_value[:3]})", "is_list": True, "is_json": False}
            elif element_type == "dict":
                return {"type": "list_dict", "description": "字典列表 (复杂JSON结构)", "is_list": True, "is_json": True}
        else:
            return {"type": "list_mixed", "description": f"混合类型列表 (包含: {', '.join(element_types)})", "is_list": True, "is_json": False}
    
    # 检测字典类型
    elif isinstance(first_value, dict):
        return {"type": "dict", "description": "字典对象 (JSON结构)", "is_list": False, "is_json": True}
    
    # 检测字符串类型（可能包含JSON）
    elif isinstance(first_value, str):
        # 尝试解析JSON
        try:
            parsed = json.loads(first_value)
            if isinstance(parsed, dict):
                return {"type": "json_str", "description": "JSON字符串 (字典)", "is_list": False, "is_json": True}
            elif isinstance(parsed, list):
                return {"type": "json_str_list", "description": "JSON字符串 (列表)", "is_list": False, "is_json": True}
        except:
            pass
        
        # 检测时间格式
        if is_time_like(first_value):
            return {"type": "time_str", "description": "时间字符串", "is_list": False, "is_json": False}
        
        # 检测数值字符串
        if is_numeric_str(first_value):
            return {"type": "numeric_str", "description": "数值字符串", "is_list": False, "is_json": False}
        
        return {"type": "str", "description": "普通字符串", "is_list": False, "is_json": False}
    
    # 检测数值类型
    elif isinstance(first_value, (int, float)):
        return {"type": "numeric", "description": "数值类型", "is_list": False, "is_json": False}
    
    else:
        return {"type": "other", "description": f"其他类型 ({type(first_value).__name__})", "is_list": False, "is_json": False}


def is_time_like(value_str):
    """检测字符串是否像时间格式"""
    if not isinstance(value_str, str):
        return False
    
    time_keywords = ['time', 'date', ':', '-', 'T', 'Z']
    return any(keyword in value_str for keyword in time_keywords) and len(value_str) > 8


def is_numeric_str(value_str):
    """检测字符串是否可转换为数值"""
    try:
        float(value_str)
        return True
    except (ValueError, TypeError):
        return False


def get_auto_analysis_panel(data_type_info, expand_lists):
    """根据数据类型自动选择分析面板"""
    data_type = data_type_info['type']
    
    # 优先检查是否为JSON相关类型，list/dict类型优先使用JSON分析
    if data_type_info['is_json'] or data_type in ["dict", "list_dict", "json_str", "json_str_list"]:
        return "JSON分析"
    
    if expand_lists and data_type_info['is_list']:
        # 展开列表的情况，根据列表元素类型选择
        if data_type == "list_str":
            return "分类分析"
        elif data_type == "list_num":
            return "数值分析"
        elif data_type == "list_dict":
            return "JSON分析"  # 字典列表优先使用JSON分析
        else:
            return "分类分析"  # 默认
    else:
        # 不展开或非列表的情况
        if data_type in ["time_str"]:
            return "时间分析"
        elif data_type in ["numeric", "numeric_str"]:
            return "数值分析"
        else:
            return "分类分析"


def execute_auto_analysis(df, cat_col, data_type_info, expand_lists):
    """执行自动分析"""
    panel = get_auto_analysis_panel(data_type_info, expand_lists)
    execute_manual_analysis(df, cat_col, panel, expand_lists)


def execute_manual_analysis(df, cat_col, panel_type, expand_lists):
    """执行手动选择的分析"""
    column_data = df[cat_col].dropna()
    if column_data.empty:
        st.warning(f"列 '{cat_col}' 中没有有效数据")
        return
    
    # 使用合并后的analyze_series_by_type函数
    analyze_series_by_type(
        data_series=column_data,
        title=cat_col,
        column_name=cat_col,
        analysis_type=panel_type,
        expand_lists=expand_lists
    )


def analyze_series_by_type(data_series, title, column_name=None, json_path=None, 
                          is_list_expanded=False, analysis_type=None, expand_lists=False, 
                          enable_json_extraction=True):
    """根据数据类型自动选择分析方法或手动指定分析类型
    
    Args:
        data_series: 要分析的数据序列
        title: 图表标题
        column_name: 原始列名（用于SQL生成等）
        json_path: JSON路径（如果适用）
        is_list_expanded: 是否已展开列表
        analysis_type: 手动指定的分析类型，如果为None则自动检测
        expand_lists: 是否展开列表进行分析
        enable_json_extraction: 是否启用JSON路径提取功能
    """
    if data_series.empty:
        return
    
    # 如果指定了分析类型，使用手动分析
    if analysis_type and analysis_type != "自动选择":
        _execute_specific_analysis(
            data_series, title, analysis_type, 
            column_name, json_path, expand_lists
        )
        return
    
    # 自动分析逻辑保持不变
    first_value = data_series.iloc[0]
    
    # 检测数据类型并选择相应分析
    if isinstance(first_value, (int, float)):
        render_numeric_analysis(data_series, f"{title} - ")
    elif isinstance(first_value, str):
        # 检测是否为时间格式
        if is_time_like(first_value):
            render_time_distribution_analysis(data_series, title)
        else:
            # 检测是否为数值字符串
            if is_numeric_str(first_value):
                numeric_data = pd.to_numeric(data_series, errors='coerce').dropna()
                if not numeric_data.empty:
                    render_numeric_analysis(numeric_data, f"{title} - ")
                else:
                    render_string_analysis(
                        data_series, 
                        f"{title} - ", 
                        show_details=True, 
                        json_path=json_path,
                        is_list_expanded=is_list_expanded,
                        column_name=column_name
                    )
            else:
                render_string_analysis(
                    data_series, 
                    f"{title} - ", 
                    show_details=True, 
                    json_path=json_path,
                    is_list_expanded=is_list_expanded,
                    column_name=column_name
                )
    elif isinstance(first_value, dict):
        # 字典类型：检查是否启用JSON提取，否则进行字典键分析
        if enable_json_extraction and analysis_type != "字典键分析":
            _render_json_path_analysis_for_series(data_series, title, column_name)
        else:
            render_dict_keys_analysis(data_series, f"{title} - ")
    elif isinstance(first_value, list):
        if expand_lists:
            # 展开列表进行分析，支持二级列表展开
            expanded_elements = _expand_nested_lists(data_series)
            if expanded_elements:
                expanded_series = pd.Series(expanded_elements)
                # 递归分析展开后的数据
                analyze_series_by_type(
                    expanded_series,
                    f"{title} (展开)",
                    column_name=column_name,
                    json_path=json_path,
                    is_list_expanded=True,
                    analysis_type=analysis_type,
                    expand_lists=False,  # 避免无限递归
                    enable_json_extraction=enable_json_extraction
                )
            else:
                st.warning(f"列表 '{title}' 展开后没有有效数据")
        else:
            # 不展开列表，检测列表中是否包含字典进行键分析
            if detect_data_contains_dicts(data_series):
                if enable_json_extraction and analysis_type != "字典键分析":
                    _render_json_path_analysis_for_series(data_series, title, column_name)
                else:
                    render_dict_keys_analysis(data_series, f"{title} - ")
            else:
                # 普通列表转为字符串分析
                str_series = data_series.astype(str)
                render_string_analysis(
                    str_series,
                    f"{title} - ",
                    show_details=True,
                    json_path=json_path,
                    is_list_expanded=is_list_expanded,
                    column_name=column_name
                )
    else:
        # 其他类型转换为字符串分析
        str_series = data_series.astype(str)
        render_string_analysis(
            str_series, 
            f"{title} - ", 
            show_details=True, 
            json_path=json_path,
            is_list_expanded=is_list_expanded,
            column_name=column_name
        )


def _execute_specific_analysis(data_series, title, analysis_type, column_name=None, 
                             json_path=None, expand_lists=False):
    """执行指定类型的分析"""
    if analysis_type == "JSON分析":
        _render_json_path_analysis_for_series(data_series, title, column_name)
    elif analysis_type == "时间分析":
        _render_time_analysis_for_series(data_series, title, expand_lists, column_name)
    elif analysis_type == "数值分析":
        _render_numeric_analysis_for_series(data_series, title, expand_lists, column_name)
    elif analysis_type == "分类分析":
        _render_categorical_analysis_for_series(data_series, title, expand_lists, column_name, json_path)
    elif analysis_type == "字典键分析":
        _render_dict_keys_analysis_for_series(data_series, title, expand_lists, column_name)
    else:
        st.error(f"未知的分析面板类型: {analysis_type}")


def _render_json_path_analysis_for_series(data_series, title, column_name=None):
    """为数据序列执行JSON路径分析"""
    # 创建临时DataFrame进行JSON分析
    temp_df = pd.DataFrame({'temp_col': data_series})
    analyzer = JsonColumnAnalyzer(temp_df, 'temp_col', f"json_analysis_{title}")
    result = analyzer.render()
    
    if result and result['success_count'] > 0:
        st.success(f"成功提取 {result['success_count']} 条数据")
        
        # 获取提取后的数据
        extracted_df = result['analysis_df']
        extracted_col = result['extracted_column']
        json_path_used = result['path_used']
        
        # 分析提取的数据类型
        extracted_data = extracted_df[extracted_col].dropna()
        
        if len(extracted_data) > 0:
            st.subheader("📊 提取数据可视化")
            
            # 递归分析提取后的数据，使用原始列名和JSON路径
            _analyze_extracted_data_recursively(
                extracted_data, 
                title, 
                json_path_used, 
                column_name
            )


def _render_time_analysis_for_series(data_series, title, expand_lists, column_name=None):
    """为数据序列执行时间分析"""
    processed_data = _preprocess_data_for_analysis(data_series, expand_lists, 'time')
    
    if processed_data.empty:
        st.warning("没有可分析的时间数据")
        return
    
    try:
        time_data = pd.to_datetime(processed_data, errors='coerce').dropna()
        if time_data.empty:
            st.warning("无法解析为时间格式")
            return
        
        render_time_distribution_analysis(time_data, title)
        
        # 额外的时间趋势分析
        if st.checkbox(f"显示时间趋势分析 - {title}", key=f"time_trend_{title}"):
            daily_data = time_data.dt.date.value_counts().sort_index()
            fig_trend = px.line(
                x=daily_data.index,
                y=daily_data.values,
                title=f"{title} - 每日数据量趋势",
                labels={'x': '日期', 'y': '数据量'}
            )
            st.plotly_chart(fig_trend, use_container_width=True)
            
    except Exception as e:
        st.error(f"时间分析出错: {str(e)}")


def _render_numeric_analysis_for_series(data_series, title, expand_lists, column_name=None):
    """为数据序列执行数值分析"""
    processed_data = _preprocess_data_for_analysis(data_series, expand_lists, 'numeric')
    
    if processed_data.empty:
        st.warning("没有可分析的数值数据")
        return
    
    # 尝试转换为数值
    numeric_data = pd.to_numeric(processed_data, errors='coerce').dropna()
    
    if numeric_data.empty:
        st.warning("无法转换为数值格式")
        return
    
    render_numeric_analysis(numeric_data, f"{title} - ")
    
    # 额外的统计信息
    st.write("**详细统计信息:**")
    col1, col2, col3, col4 = st.columns(4)
    with col1:
        st.metric("平均值", f"{numeric_data.mean():.2f}")
    with col2:
        st.metric("中位数", f"{numeric_data.median():.2f}")
    with col3:
        st.metric("标准差", f"{numeric_data.std():.2f}")
    with col4:
        st.metric("变异系数", f"{(numeric_data.std()/numeric_data.mean()*100):.1f}%")


def _render_categorical_analysis_for_series(data_series, title, expand_lists, column_name=None, json_path=None):
    """为数据序列执行分类分析"""
    processed_data = _preprocess_data_for_analysis(data_series, expand_lists, 'categorical')
    
    if processed_data.empty:
        st.warning("没有可分析的分类数据")
        return
    
    render_string_analysis(
        processed_data, 
        f"{title} - ", 
        show_details=True, 
        json_path=json_path,
        is_list_expanded=expand_lists,
        column_name=column_name
    )


def _render_dict_keys_analysis_for_series(data_series, title, expand_lists, column_name=None):
    """为数据序列执行字典键分析"""
    # 提取字典数据
    dict_data = []
    for value in data_series.dropna():
        if isinstance(value, dict):
            dict_data.append(value)
        elif isinstance(value, list) and expand_lists:
            for item in value:
                if isinstance(item, dict):
                    dict_data.append(item)
        elif isinstance(value, str):
            try:
                parsed = json.loads(value)
                if isinstance(parsed, dict):
                    dict_data.append(parsed)
                elif isinstance(parsed, list) and expand_lists:
                    for item in parsed:
                        if isinstance(item, dict):
                            dict_data.append(item)
            except:
                continue
    
    if dict_data:
        render_dict_keys_analysis(dict_data, f"{title} - ")
    else:
        st.warning(f"在 '{title}' 中未找到字典数据")


def _preprocess_data_for_analysis(data_series, expand_lists, target_type):
    """预处理数据用于特定类型的分析"""
    if not expand_lists:
        return data_series
    
    expanded_elements = []
    
    for value in data_series.dropna():
        if isinstance(value, list):
            if target_type == 'numeric':
                # 数值分析时，只扩展数值列表
                expanded_elements.extend([x for x in value if isinstance(x, (int, float))])
            elif target_type == 'time':
                # 时间分析时，只扩展字符串
                expanded_elements.extend([str(x) for x in value if isinstance(x, str)])
            else:
                # 分类分析时，扩展所有元素
                expanded_elements.extend([str(x) for x in value])
        else:
            expanded_elements.append(value)
    
    return pd.Series(expanded_elements) if expanded_elements else pd.Series([])


# 以下是分析渲染函数的简化版本，实际项目中可能需要根据具体需求进一步实现
def render_numeric_analysis(data_series, title_prefix=""):
    """渲染数值分析"""
    col1, col2 = st.columns(2)
    
    with col1:
        # 直方图
        fig_hist = px.histogram(
            x=data_series,
            title=f"{title_prefix}数值分布直方图",
            labels={"x": "数值", "count": "频次"}
        )
        st.plotly_chart(fig_hist, use_container_width=True)
    
    with col2:
        # 箱线图
        fig_box = px.box(
            y=data_series,
            title=f"{title_prefix}数值箱线图",
            labels={"y": "数值"}
        )
        st.plotly_chart(fig_box, use_container_width=True)


def render_string_analysis(data_series, title_prefix="", show_details=True, 
                         json_path=None, is_list_expanded=False, column_name=None):
    """渲染字符串数据分析的通用函数

    Args:
        data_series: pandas Series，包含字符串数据
        title_prefix: 图表标题前缀
        show_details: 是否显示详细统计表
        json_path: JSON路径（如果是从JSON提取的数据）
        is_list_expanded: 是否为列表展开的数据
        column_name: 原始列名（用于SQL生成）
    """
    value_counts = data_series.value_counts().head(20)
    
    if len(value_counts) > 1:
        col1, col2 = st.columns(2)
        
        with col1:
            fig_bar = px.bar(
                x=value_counts.values,
                y=value_counts.index,
                orientation='h',
                title=f"{title_prefix}频次分布",
                labels={'x': '频次', 'y': '值'}
            )
            st.plotly_chart(fig_bar, use_container_width=True)
        
        with col2:
            # 只显示前10个以避免饼图过于复杂
            top10_counts = value_counts.head(10)
            fig_pie = px.pie(
                values=top10_counts.values,
                names=top10_counts.index,
                title=f"{title_prefix}占比 Top 10"
            )
            st.plotly_chart(fig_pie, use_container_width=True)
        
        if show_details:
            # 增强的分布详情 - 支持分页和多选
            st.write("**📋 交互式数据筛选**")
            
            # 构建稳定唯一的key前缀：视图+列名+路径信息
            view_name = "data_analysis"
            component_name = "string_filter"
            
            if json_path and column_name:
                if is_list_expanded:
                    key_suffix = f"{column_name}_{json_path}_expanded"
                else:
                    key_suffix = f"{column_name}_{json_path}"
            elif column_name:
                key_suffix = column_name
            else:
                # 备用方案：基于标题前缀
                key_suffix = str(hash(title_prefix))[:8]
            
            # 清理key_suffix中的特殊字符
            key_suffix = key_suffix.replace('/', '_').replace('.', '_').replace('[', '_').replace(']', '_')
            key_prefix = f"{view_name}_{component_name}_{key_suffix}"
            
            data_selector = InteractiveDataSelector(key_prefix)
            selected_values = data_selector.render_data_selector(
                data_series, 
                title="选择要筛选的数据值",
                page_size=15
            )
            
            # 显示选择总结
            if selected_values:
                data_selector.render_selection_summary(selected_values, data_series)
            
            # 如果有选中的数据，生成SQL
            if selected_values and column_name:
                st.divider()
                
                # 确定表名
                table_name = "data"
                if 'tables' in st.session_state and st.session_state.tables:
                    # 多表模式，需要确定具体表名
                    # 这里简化处理，使用data1
                    table_name = "data1"
                
                sql_generator = DataAnalysisSqlGenerator(table_name)
                
                # 生成两种SQL：筛选和聚合
                tab1, tab2 = st.tabs(["🔍 数据筛选SQL", "📊 数据统计SQL"])
                
                with tab1:
                    filter_sql = sql_generator.generate_value_filter_sql(
                        column_name, 
                        selected_values, 
                        json_path, 
                        is_list_expanded
                    )
                    sql_generator.render_sql_display(filter_sql, "筛选选中值的SQL查询")
                
                with tab2:
                    agg_sql = sql_generator.generate_aggregation_sql(
                        column_name, 
                        selected_values, 
                        json_path, 
                        is_list_expanded
                    )
                    sql_generator.render_sql_display(agg_sql, "聚合统计SQL查询")
            
            elif not column_name:
                st.info("💡 提示: 需要提供列名信息才能生成SQL语句")
    else:
        # 只有一个或没有分类值的情况
        st.info(f"数据只有 {len(value_counts)} 个不同的值")
        if len(value_counts) > 0:
            st.write("**数据分布:**")
            stats_df = pd.DataFrame({
                '值': value_counts.index,
                '数量': value_counts.values,
                '占比(%)': (value_counts.values / len(data_series) * 100).round(2)
            })
            st.dataframe(stats_df, width='stretch')


def render_time_distribution_analysis(data_series, title):
    """渲染时间分布分析"""
    try:
        time_data = pd.to_datetime(data_series, errors='coerce').dropna()
        if time_data.empty:
            st.warning("无法解析时间数据")
            return
        
        # 时间分布直方图
        fig = px.histogram(
            x=time_data,
            title=f"{title} - 时间分布",
            labels={"x": "时间", "count": "频次"}
        )
        st.plotly_chart(fig, use_container_width=True)
    except Exception as e:
        st.error(f"时间分析出错: {str(e)}")


def render_dict_keys_analysis_for_column(df, col_name, expand_lists):
    """列字典键分析"""
    st.subheader("🔑 字典键分析")
    
    column_data = df[col_name].dropna()
    if column_data.empty:
        st.warning(f"列 '{col_name}' 中没有有效数据")
        return
    
    # 提取字典数据进行分析
    dict_data = []
    for value in column_data:
        if isinstance(value, dict):
            dict_data.append(value)
        elif isinstance(value, list) and expand_lists:
            # 如果选择展开列表，提取列表中的字典
            for item in value:
                if isinstance(item, dict):
                    dict_data.append(item)
        elif isinstance(value, str):
            # 尝试解析JSON字符串
            try:
                parsed = json.loads(value)
                if isinstance(parsed, dict):
                    dict_data.append(parsed)
                elif isinstance(parsed, list) and expand_lists:
                    for item in parsed:
                        if isinstance(item, dict):
                            dict_data.append(item)
            except:
                continue
    
    if dict_data:
        render_dict_keys_analysis(dict_data, f"{col_name} - ")
    else:
        st.warning(f"列 '{col_name}' 中未找到字典数据")


def render_dict_keys_analysis(dict_elements, title_prefix):
    """渲染字典键分析的通用函数
    
    Args:
        dict_elements: 包含字典的列表或Series
        title_prefix: 图表标题前缀
    """
    # 提取所有字典的键
    all_keys = []
    
    # 处理Series或list输入
    if hasattr(dict_elements, '__iter__') and not isinstance(dict_elements, str):
        for item in dict_elements:
            if isinstance(item, dict):
                all_keys.extend(item.keys())
            elif isinstance(item, list):
                # 处理字典列表
                for sub_item in item:
                    if isinstance(sub_item, dict):
                        all_keys.extend(sub_item.keys())
    
    if all_keys:
        key_counts = pd.Series(all_keys).value_counts().head(15)
        
        col1, col2 = st.columns(2)
        
        with col1:
            fig_bar = px.bar(
                x=key_counts.values,
                y=key_counts.index,
                orientation='h',
                title=f"{title_prefix}字典键频次分布",
                labels={'x': '频次', 'y': '键名'}
            )
            st.plotly_chart(fig_bar, use_container_width=True)
        
        with col2:
            fig_pie = px.pie(
                values=key_counts.values,
                names=key_counts.index,
                title=f"{title_prefix}字典键占比分布"
            )
            st.plotly_chart(fig_pie, use_container_width=True)
    else:
        st.warning("未找到有效的字典数据")


def _expand_nested_lists(data_series, max_depth=2):
    """展开嵌套列表，支持二级列表展开 list[list[str]]
    
    Args:
        data_series: 包含列表的数据序列
        max_depth: 最大展开深度，默认为2
    
    Returns:
        list: 展开后的元素列表
    """
    expanded_elements = []
    
    for value in data_series.dropna():
        _expand_value_recursively(value, expanded_elements, current_depth=0, max_depth=max_depth)
    
    return expanded_elements


def _expand_value_recursively(value, result_list, current_depth=0, max_depth=2):
    """递归展开值，支持多级嵌套列表"""
    
    if current_depth >= max_depth:
        # 达到最大深度，直接转为字符串
        result_list.append(str(value))
        return
    
    if isinstance(value, list):
        for item in value:
            _expand_value_recursively(item, result_list, current_depth + 1, max_depth)
    elif isinstance(value, np.ndarray):
        try:
            list_value = value.tolist()
            _expand_value_recursively(list_value, result_list, current_depth, max_depth)
        except:
            result_list.append(str(value))
    else:
        # 非列表类型，直接添加
        result_list.append(value)


def _render_json_path_analysis_for_series(data_series, title, column_name=None):
    """为数据序列执行JSON路径分析并递归分析提取结果
    
    Args:
        data_series: 包含JSON数据的序列
        title: 分析标题
        column_name: 原始列名，用于SQL生成
    """
    st.subheader(f"🔍 JSON路径提取分析 - {title}")
    
    # 创建临时DataFrame进行JSON分析
    temp_df = pd.DataFrame({'temp_col': data_series})
    analyzer = JsonColumnAnalyzer(temp_df, 'temp_col', f"json_analysis_{title}")
    result = analyzer.render()
    
    if result and result['success_count'] > 0:
        st.success(f"✅ 成功提取 {result['success_count']} 条数据")
        
        # 获取提取后的数据
        extracted_df = result['analysis_df']
        extracted_col = result['extracted_column']
        json_path_used = result['path_used']
        
        # 分析提取的数据类型
        extracted_data = extracted_df[extracted_col].dropna()
        
        if len(extracted_data) > 0:
            st.subheader("📊 提取数据可视化")
            
            # 递归分析提取后的数据
            _analyze_extracted_data_recursively(
                extracted_data, 
                title, 
                json_path_used, 
                column_name
            )
        else:
            st.warning("⚠️ 提取的数据为空")
    else:
        st.info("💡 请输入JSON路径来提取特定字段进行分析")


def _analyze_extracted_data_recursively(extracted_data, original_title, json_path, column_name=None):
    """递归分析JSON提取出的数据
    
    Args:
        extracted_data: 提取后的数据序列
        original_title: 原始标题
        json_path: 使用的JSON路径
        column_name: 原始列名
    """
    if extracted_data.empty:
        st.warning("⚠️ 提取的数据为空")
        return
    
    sample_extracted = extracted_data.dropna()
    if sample_extracted.empty:
        return
    
    first_extracted = sample_extracted.iloc[0]
    
    # 根据提取结果的类型选择分析策略
    if isinstance(first_extracted, list):
        st.info("📋 检测到提取结果为列表类型，将自动展开分析")
        # 使用analyze_series_by_type，设置expand_lists=True
        analyze_series_by_type(
            extracted_data, 
            f"{original_title}[{json_path}]", 
            column_name=column_name,
            json_path=json_path,
            is_list_expanded=False,  # 这里还没展开
            expand_lists=True,  # 让analyze_series_by_type自动展开
            enable_json_extraction=True  # 允许进一步JSON提取
        )
    elif isinstance(first_extracted, dict):
        st.info("🔍 检测到提取结果为字典类型，可继续提取")
        # 对字典类型使用JSON分析
        analyze_series_by_type(
            extracted_data, 
            f"{original_title}[{json_path}]", 
            column_name=column_name,
            json_path=json_path,
            is_list_expanded=False,
            analysis_type="JSON分析",
            enable_json_extraction=True
        )
    else:
        # 标量数据，直接分析
        analyze_series_by_type(
            extracted_data, 
            f"{original_title}[{json_path}]", 
            column_name=column_name,
            json_path=json_path,
            is_list_expanded=False,
            enable_json_extraction=False  # 标量数据不需要JSON提取
        )


def detect_data_contains_dicts(data_series):
    """检测数据是否包含字典结构"""
    if data_series.empty:
        return False
    
    sample_data = data_series.dropna().head(10)
    dict_count = 0
    
    for value in sample_data:
        if isinstance(value, dict):
            dict_count += 1
        elif isinstance(value, list) and len(value) > 0:
            # 检查列表中是否包含字典
            if any(isinstance(item, dict) for item in value[:3]):  # 只检查前3个元素
                dict_count += 1
        elif isinstance(value, str):
            # 检查JSON字符串中是否包含字典
            try:
                parsed = json.loads(value)
                if isinstance(parsed, dict) or (isinstance(parsed, list) and 
                    len(parsed) > 0 and isinstance(parsed[0], dict)):
                    dict_count += 1
            except:
                continue
    
    # 如果超过30%的样本包含字典，认为适合字典键分析
    return dict_count / len(sample_data) >= 0.3