from collections.abc import Iterable

import pandas as pd

from sangreal_wind.utils.base_api import IndexDataAPI, validate_index_codes
from sangreal_wind.utils.config_manager import WIND_DB


class NormalIndexAPI(IndexDataAPI):
    """普通指数数据API"""

    def get_table_name(self) -> str:
        return "AINDEXEODPRICES"


class ZXIndexAPI(IndexDataAPI):
    """中信指数数据API"""

    def get_table_name(self) -> str:
        return "AINDEXINDUSTRIESEODCITICS"


class WindIndexAPI(IndexDataAPI):
    """Wind行业指数数据API"""

    def get_table_name(self) -> str:
        return "AINDEXWINDINDUSTRIESEOD"


class SWIndexAPI(IndexDataAPI):
    """申万指数数据API"""

    def get_table_name(self) -> str:
        return "ASWSINDEXEOD"


# 创建API实例
_normal_api = NormalIndexAPI()
_zx_api = ZXIndexAPI()
_wind_api = WindIndexAPI()
_sw_api = SWIndexAPI()


def get_index_data_tmp(
    index_list=None, index_type="normal", begin_dt="20010101", end_dt="20990101"
):
    """
    获取指定类型的指数数据

    Args:
        index_list: 指数列表
        index_type: 指数类型 (normal, zx, wind, sw)
        begin_dt: 开始日期
        end_dt: 结束日期

    Returns:
        DataFrame: 包含OHLCV数据的DataFrame
    """
    # 根据指数类型选择相应的API
    api_map = {
        "normal": _normal_api,
        "zx": _zx_api,
        "wind": _wind_api,
        "sw": _sw_api
    }

    api = api_map.get(index_type)
    if api is None:
        raise ValueError(f"Unsupported index_type: {index_type}. Supported types: {list(api_map.keys())}")

    return api.get_ohlcv_data(index_list, begin_dt, end_dt)


def get_index_data(index_list, begin_dt="20010101", end_dt="20990101"):
    """[获取指数数据 高开低收]

    Arguments:
        index_list {[str or list]} -- [windcode of index_list]

    Keyword Arguments:
        begin_dt {[str]} -- [description] (default: {'20010101'})
        end_dt {[str]} -- [description] (default: {'20990101'})

    Returns:
        [pd.DataFrame] -- ['sid', 'trade_dt', 's_open', 's_high', 's_low', 's_close', 's_volume', 's_amount']
    """
    # 验证并标准化指数代码列表
    index_set = validate_index_codes(index_list)

    # 根据后缀自动分类指数
    sw_list = set(i for i in index_set if i.endswith("SI"))
    zx_list = set(i for i in index_set if i.startswith("CI"))
    wind_list = set(i for i in index_set if i.startswith("88"))
    n_list = index_set - sw_list - zx_list - wind_list

    # 使用缓存的API获取各类指数数据（将set转换为frozenset以支持缓存）
    data_frames = []

    if sw_list:
        data_frames.append(_sw_api.get_ohlcv_data(frozenset(sw_list), begin_dt, end_dt))
    if wind_list:
        data_frames.append(_wind_api.get_ohlcv_data(frozenset(wind_list), begin_dt, end_dt))
    if zx_list:
        data_frames.append(_zx_api.get_ohlcv_data(frozenset(zx_list), begin_dt, end_dt))
    if n_list:
        data_frames.append(_normal_api.get_ohlcv_data(frozenset(n_list), begin_dt, end_dt))

    # 合并所有DataFrame
    if data_frames:
        df = pd.concat(data_frames, axis=0, ignore_index=True, sort=False)
        # 按交易日期和股票代码排序，保持输出一致性
        df = df.sort_values(['trade_dt', 'sid']).reset_index(drop=True)
        return df
    else:
        return pd.DataFrame(columns=['sid', 'trade_dt', 's_open', 's_high', 's_low', 's_close', 's_volume', 's_amount'])


if __name__ == "__main__":
    print(
        get_index_data(
            "000001.SH",
        )
    )
