# -*- coding: utf-8 -*-
"""
Core 维度同步任务

功能说明：
    将 DWD 层当前版本（scd2_is_current=1）的维度数据同步到 core 层。
    core 层作为跨平台统一维度层，屏蔽 ODS/DWD 多数据源差异。

同步表：
    - core.dim_assistant  <- dwd.dim_assistant
    - core.dim_member     <- dwd.dim_member
    - core.dim_site       <- dwd.dim_site
    - core.dim_table      <- dwd.dim_table

更新策略：
    TRUNCATE + INSERT 全量刷新（维度表数据量小，全量代价低）

作者：ETL 团队
创建日期：2026-04-15
"""

from __future__ import annotations

from typing import Any, Dict, List

from .base_dws_task import BaseDwsTask, TaskContext


# 同步映射：(core 表, DWD 源表, 字段映射)
# 字段映射格式：(core_col, dwd_expr)
SYNC_TABLES = [
    {
        "core_table": "core.dim_assistant",
        "dwd_source": "dwd.dim_assistant",
        "columns": [
            ("assistant_id", "assistant_id"),
            ("tenant_id", "tenant_id"),
            ("site_id", "site_id"),
            ("real_name", "real_name"),
            ("nickname", "nickname"),
            ("mobile", "mobile"),
            ("level", "level"),
            ("assistant_status", "assistant_status"),
            ("leave_status", "leave_status"),
        ],
    },
    {
        "core_table": "core.dim_member",
        "dwd_source": "dwd.dim_member",
        "columns": [
            ("member_id", "member_id"),
            ("system_member_id", "system_member_id"),
            ("tenant_id", "tenant_id"),
            ("register_site_id", "register_site_id"),
            ("mobile", "mobile"),
            ("nickname", "nickname"),
            ("member_card_grade_name", "member_card_grade_name"),
            ("status", "1"),  # DWD 无 status 字段，scd2_is_current=1 即有效
        ],
    },
    {
        "core_table": "core.dim_site",
        "dwd_source": "dwd.dim_site",
        "columns": [
            ("site_id", "site_id"),
            ("tenant_id", "tenant_id"),
            ("shop_name", "shop_name"),
            ("site_label", "site_label"),
            ("shop_status", "shop_status"),
        ],
    },
    {
        "core_table": "core.dim_table",
        "dwd_source": "dwd.dim_table",
        "columns": [
            ("table_id", "table_id"),
            ("site_id", "site_id"),
            ("table_name", "table_name"),
            ("site_table_area_name", "site_table_area_name"),
            ("table_price", "table_price"),
        ],
    },
]


class CoreDimSyncTask(BaseDwsTask):
    """Core 维度同步任务：DWD -> core 全量刷新"""

    # 无日期列，全量刷新
    DATE_COL = None

    def get_task_code(self) -> str:
        return "CORE_DIM_SYNC"

    def get_target_table(self) -> str:
        # 多表同步，此方法不直接使用
        return "core_dim_sync"

    def get_primary_keys(self) -> List[str]:
        return []

    def extract(self, context: TaskContext) -> Dict[str, Any]:
        """提取 DWD 当前版本维度数据"""
        result = {}
        for table_def in SYNC_TABLES:
            core_table = table_def["core_table"]
            dwd_source = table_def["dwd_source"]
            dwd_exprs = [col[1] for col in table_def["columns"]]

            select_clause = ", ".join(dwd_exprs)
            sql = f"SELECT {select_clause} FROM {dwd_source} WHERE scd2_is_current = 1"

            with self.db.conn.cursor() as cur:
                cur.execute(sql)
                rows = cur.fetchall()

            core_cols = [col[0] for col in table_def["columns"]]
            result[core_table] = {
                "rows": [dict(zip(core_cols, row)) for row in rows],
                "columns": core_cols,
            }
            self.logger.info(
                "%s: %s <- %s: %d rows",
                self.get_task_code(), core_table, dwd_source, len(rows),
            )

        return {"tables": result, "site_id": context.store_id}

    def transform(self, extracted: Dict[str, Any], context: TaskContext) -> Dict[str, Any]:
        """直通，无需转换"""
        return extracted

    def load(self, transformed: Dict[str, Any], context: TaskContext) -> dict:
        """TRUNCATE + INSERT 全量刷新"""
        tables = transformed.get("tables", {})
        total_inserted = 0
        total_deleted = 0

        for core_table, data in tables.items():
            rows = data["rows"]
            columns = data["columns"]

            with self.db.conn.cursor() as cur:
                # TRUNCATE
                cur.execute(f"TRUNCATE {core_table}")
                self.logger.info("%s: TRUNCATE %s", self.get_task_code(), core_table)

                # INSERT
                if rows:
                    cols_str = ", ".join(columns)
                    placeholders = ", ".join(["%s"] * len(columns))
                    insert_sql = f"INSERT INTO {core_table} ({cols_str}) VALUES ({placeholders})"

                    for row in rows:
                        values = [row.get(col) for col in columns]
                        cur.execute(insert_sql, values)

                total_inserted += len(rows)
                self.logger.info(
                    "%s: INSERT %s: %d rows",
                    self.get_task_code(), core_table, len(rows),
                )

        return {
            "counts": {
                "fetched": total_inserted,
                "inserted": total_inserted,
                "updated": 0,
                "skipped": 0,
                "errors": 0,
            },
            "extra": {"tables_synced": len(tables)},
        }
