from ...sync_system.strategy import DefaultSyncStrategy
from ...sync_system.config import StrategyConfig, OrphanAction, UpdateDirection
from ...sync_system.strategy_ops.compare_ops import normalized_data_for_compare, collect_payload_diffs
from schemas.project_extensions.production import ProductionDetail, PostProduction


class ProductionSyncStrategy(DefaultSyncStrategy[ProductionDetail]):
    """
    Production 同步策略（项目扩展）。
    """

    schema = ProductionDetail

    default_config = StrategyConfig(
        auto_bind=True,
        auto_bind_fields=["project_id", "code"],
        depend_fields={"project_id": "project"},
        local_orphan_action=OrphanAction.NONE,
        remote_orphan_action=OrphanAction.NONE,
        update_direction=UpdateDirection.PUSH,
    )

    def _needs_update(self, source_node, target_node, resolved_data=None, data_id_map=None) -> bool:
        if resolved_data is None:
            raise ValueError(f"[{self.node_type}] resolved_data is required for differential sync.")

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

        update_fields = set(PostProduction.model_fields.keys())
        source_payload = {key: value for key, value in resolved_data.items() if key in update_fields}
        target_payload = {key: value for key, value in target_data.items() if key in update_fields}

        normalized_source = normalized_data_for_compare(source_payload, data_id_map or {})
        normalized_target = normalized_data_for_compare(target_payload, data_id_map or {})
        diff_map = collect_payload_diffs(normalized_source, normalized_target, max_items=8)
        return bool(diff_map)