from ...sync_system.strategy import DefaultSyncStrategy
from ...sync_system.config import StrategyConfig, OrphanAction, UpdateDirection
from schemas.supplier.supplier import SupplierDetailResponse


class SupplierSyncStrategy(DefaultSyncStrategy[SupplierDetailResponse]):
    """
    Supplier 同步策略（基础数据，仅拉取）。
    
    注意：Supplier 数据量大（约 60000 条），同步耗时较长。
        建议通过 datasource.handler_configs 控制 handler 参数，例如：
        - remote_datasource.handler_configs.supplier.load_mode = "persisted_only"
            API handler 跳过远端拉取，仅使用持久化数据。
    """

    schema = SupplierDetailResponse

    default_config = StrategyConfig(
        auto_bind=True,
        auto_bind_fields=["credit_code"],
        depend_fields={},
        local_orphan_action=OrphanAction.NONE,
        remote_orphan_action=OrphanAction.CREATE_LOCAL,
        update_direction=UpdateDirection.PULL,
    )

    def _needs_update(
        self,
        source_node,
        target_node,
        resolved_data=None,
        data_id_map=None,
    ) -> bool:
        """Supplier 更新忽略 id 字段差异。"""
        if resolved_data is None:
            raise ValueError(f"[{self.node_type}] resolved_data is required for differential sync.")

        source_data = resolved_data
        target_data = target_node.get_data()
        if source_data is None or target_data is None:
            return False

        is_different = False
        diffs = []
        for k, v1 in source_data.items():
            if k == "id":
                continue
            v2 = target_data.get(k)
            if v1 != v2:
                is_different = True
                diffs.append(f"{k}: {v1} != {v2}")

        if is_different and diffs:
            print(f"  [DEBUG] [{self.node_type}] Node diff detected: {', '.join(diffs[:5])}")

        return is_different
