"""财务数据统一同步调度中心。

该模块作为财务数据同步的调度中心，只负责任务协调和调度。
具体的同步逻辑已下沉到各 API 文件中。

支持的财务数据类型:
- income: 利润表 (已实现)
- balance: 资产负债表 (已实现)
- cashflow: 现金流量表 (已实现)
- fina_indicator: 财务指标 (已实现)

使用方式:
    # 同步所有财务数据（增量）
    from src.data.api_wrappers.financial_data.api_financial_sync import sync_financial
    sync_financial()

    # 全量同步
    sync_financial(force_full=True)

    # 只同步利润表
    sync_financial(data_types=["income"])

    # 只同步资产负债表
    sync_financial(data_types=["balance"])

    # 只同步现金流量表
    sync_financial(data_types=["cashflow"])

    # 只同步财务指标
    sync_financial(data_types=["fina_indicator"])

    # 预览同步
    from src.data.api_wrappers.financial_data.api_financial_sync import preview_sync
    preview = preview_sync()
"""

from typing import List, Optional

from src.data.sync_logger import SyncLogManager
from src.data.sync_config import get_rate_limit, get_threads
from src.data.api_wrappers.financial_data.api_income import (
    IncomeQuarterSync,
    sync_income,
    preview_income_sync,
)
from src.data.api_wrappers.financial_data.api_balance import (
    BalanceQuarterSync,
    sync_balance,
    preview_balance_sync,
)
from src.data.api_wrappers.financial_data.api_cashflow import (
    CashflowQuarterSync,
    sync_cashflow,
    preview_cashflow_sync,
)
from src.data.api_wrappers.financial_data.api_fina_indicator import (
    FinaIndicatorQuarterSync,
    sync_fina_indicator,
    preview_fina_indicator_sync,
)


# 支持的财务数据类型映射
FINANCIAL_SYNCERS = {
    "income": {
        "syncer_class": IncomeQuarterSync,
        "sync_func": sync_income,
        "preview_func": preview_income_sync,
        "display_name": "利润表",
    },
    "balance": {
        "syncer_class": BalanceQuarterSync,
        "sync_func": sync_balance,
        "preview_func": preview_balance_sync,
        "display_name": "资产负债表",
    },
    "cashflow": {
        "syncer_class": CashflowQuarterSync,
        "sync_func": sync_cashflow,
        "preview_func": preview_cashflow_sync,
        "display_name": "现金流量表",
    },
    "fina_indicator": {
        "syncer_class": FinaIndicatorQuarterSync,
        "sync_func": sync_fina_indicator,
        "preview_func": preview_fina_indicator_sync,
        "display_name": "财务指标",
    },
}


def sync_financial(
    data_types: Optional[List[str]] = None,
    force_full: bool = False,
    dry_run: bool = False,
) -> dict[str, list]:
    """同步财务数据（调度函数）。

    根据指定的数据类型，调度对应的同步器执行同步。

    Args:
        data_types: 数据类型列表，如 ["income", "balance"]
                   None 表示同步所有类型
        force_full: 若为 True，强制全量同步
        dry_run: 若为 True，仅预览不写入

    Returns:
        各类型同步结果字典 {数据类型: 同步结果列表}

    Example:
        >>> # 同步所有财务数据
        >>> sync_financial()
        >>>
        >>> # 只同步利润表
        >>> sync_financial(data_types=["income"])
        >>>
        >>> # 全量同步
        >>> sync_financial(force_full=True)
    """
    if data_types is None:
        data_types = list(FINANCIAL_SYNCERS.keys())

    results = {}

    # 初始化日志管理器并记录调度中心开始
    log_manager = SyncLogManager()
    log_entry = log_manager.start_sync(
        table_name="financial_data_batch",
        sync_type="full" if force_full else "incremental",
        metadata={"data_types": data_types, "dry_run": dry_run},
    )

    print("\n" + "=" * 60)
    print("[Financial Sync] 财务数据同步调度中心")
    print("=" * 60)
    print(f"数据类型: {', '.join(data_types)}")
    print(f"同步模式: {'全量' if force_full else '增量'}")
    print(f"写入模式: {'预览' if dry_run else '实际写入'}")
    print("=" * 60)

    total_inserted = 0
    failed_types = []

    for data_type in data_types:
        if data_type not in FINANCIAL_SYNCERS:
            print(f"[WARN] 未知的数据类型: {data_type}")
            results[data_type] = {"error": f"Unknown data type: {data_type}"}
            failed_types.append(data_type)
            continue

        config = FINANCIAL_SYNCERS[data_type]
        sync_func = config["sync_func"]
        display_name = config["display_name"]

        # 获取当前接口的 rate limit
        rate_limit = get_rate_limit(data_type)
        threads = get_threads(data_type)

        print(f"\n[{display_name}] 开始同步...")
        print(f"  Rate Limit: {rate_limit}/min, Threads: {threads}")

        try:
            result = sync_func(force_full=force_full, dry_run=dry_run)
            results[data_type] = result

            # 统计插入的记录数
            if isinstance(result, list):
                inserted = sum(
                    r.get("inserted_count", 0) for r in result if isinstance(r, dict)
                )
                total_inserted += inserted

            print(f"[{display_name}] 同步完成")
        except Exception as e:
            print(f"[ERROR] [{display_name}] 同步失败: {e}")
            results[data_type] = {"error": str(e)}
            failed_types.append(data_type)

    # 打印汇总
    print("\n" + "=" * 60)
    print("[Financial Sync] 同步汇总")
    print("=" * 60)
    for data_type, result in results.items():
        if "error" in result:
            status = f"失败: {result['error']}"
        elif isinstance(result, list):
            total_records = sum(
                r.get("diff_count", 0) for r in result if isinstance(r, dict)
            )
            status = f"成功 ({len(result)} 个季度, {total_records} 条差异)"
        else:
            status = "完成"

        display_name = FINANCIAL_SYNCERS.get(data_type, {}).get(
            "display_name", data_type
        )
        print(f"  {display_name}: {status}")
    print("=" * 60)

    # 完成调度中心日志记录
    status = "failed" if failed_types else "success"
    error_msg = f"Failed types: {failed_types}" if failed_types else None
    log_manager.complete_sync(
        log_entry,
        status=status,
        records_inserted=total_inserted,
        error_message=error_msg,
    )

    return results


def preview_sync(data_types: Optional[List[str]] = None) -> dict[str, dict]:
    """预览财务数据同步信息。

    Args:
        data_types: 数据类型列表，None 表示所有类型

    Returns:
        各类型预览信息字典

    Example:
        >>> preview = preview_sync()
        >>> print(preview)
    """
    if data_types is None:
        data_types = list(FINANCIAL_SYNCERS.keys())

    previews = {}

    print("\n" + "=" * 60)
    print("[Financial Sync] 同步预览")
    print("=" * 60)

    for data_type in data_types:
        if data_type not in FINANCIAL_SYNCERS:
            continue

        preview_func = FINANCIAL_SYNCERS[data_type]["preview_func"]
        previews[data_type] = preview_func()

    return previews


def list_financial_types() -> list[dict]:
    """列出所有支持的财务数据类型。

    Returns:
        数据类型信息列表
    """
    return [
        {
            "name": name,
            "display_name": config["display_name"],
        }
        for name, config in FINANCIAL_SYNCERS.items()
    ]


# 保持向后兼容的别名
sync_all_financial = sync_financial


if __name__ == "__main__":
    import sys

    print("=" * 60)
    print("财务数据同步调度中心")
    print("=" * 60)
    print("\n支持的财务数据类型:")
    print("-" * 60)

    for info in list_financial_types():
        print(f"  - {info['name']}: {info['display_name']}")

    print("-" * 60)
    print("\n使用方式:")
    print("  # 同步所有财务数据（默认）")
    print("  python api_financial_sync.py")
    print("")
    print("  # 全量同步")
    print("  python api_financial_sync.py --full")
    print("")
    print("  # 预览模式")
    print("  python api_financial_sync.py --preview")
    print("")
    print("  # Python 代码调用")
    print(
        "  from src.data.api_wrappers.financial_data.api_financial_sync import sync_financial"
    )
    print("  sync_financial()")
    print("=" * 60)

    # 默认执行同步
    if len(sys.argv) > 1 and sys.argv[1] == "--preview":
        print("\n执行预览...")
        preview_sync()
    else:
        print("\n执行同步...")
        force_full = "--full" in sys.argv
        sync_financial(force_full=force_full)
