from ...sync_system.strategy import DefaultSyncStrategy
from ...sync_system.config import StrategyConfig, OrphanAction, UpdateDirection
from schemas.project_extensions.project_detail import ProjectDetailKey, ProjectDetailProject


class ProjectDetailSyncStrategy(DefaultSyncStrategy[ProjectDetailProject]):
    """
    ProjectDetail 同步策略（项目容量信息）。

    默认行为：
    - plan_construction / actual_construction / production → push（本地 → 远程）
    - ensure_production / climb_production / challenge_production → pull（远程 → 本地）
    """

    schema = ProjectDetailProject

    default_config = StrategyConfig(
        auto_bind=True,
        auto_bind_fields=["project_id", "key"],
        depend_fields={"project_id": "project"},
        local_orphan_action=OrphanAction.NONE,
        remote_orphan_action=OrphanAction.NONE,
        update_direction=UpdateDirection.PUSH,
        field_direction_key="key",
        field_direction_overrides={
            "ensure_production": UpdateDirection.PULL,
            "climb_production": UpdateDirection.PULL,
            "challenge_production": UpdateDirection.PULL,
        },
    )

    def preprocess_compare_payload(self, payload: dict) -> dict:
        normalized = dict(payload or {})
        key = normalized.get("key")
        if isinstance(key, ProjectDetailKey):
            key = key.value
            normalized["key"] = key
        if isinstance(key, str):
            normalized["value"] = self._normalize_detail_value_for_compare(key, normalized.get("value"))
        return normalized

    @staticmethod
    def _normalize_detail_value_for_compare(key: str, value: object) -> list[dict[str, object]]:
        if not isinstance(value, list):
            return []

        items: list[dict[str, object]] = []
        for item in value:
            if not isinstance(item, dict):
                continue

            normalized_item: dict[str, object] = {}
            if "capacity" in item:
                normalized_item["capacity"] = item.get("capacity")

            if key in {"plan_construction", "actual_construction", "production"}:
                date_value = item.get("date")
                if date_value in (None, ""):
                    continue
                normalized_item["date"] = date_value
            elif key in {"ensure_production", "climb_production", "challenge_production"}:
                year_value = item.get("year")
                if year_value in (None, ""):
                    date_value = item.get("date")
                    if isinstance(date_value, str) and len(date_value) >= 4 and date_value[:4].isdigit():
                        year_value = int(date_value[:4])
                if year_value in (None, ""):
                    continue
                normalized_item["year"] = year_value
            else:
                if item.get("year") not in (None, ""):
                    normalized_item["year"] = item.get("year")
                if item.get("date") not in (None, ""):
                    normalized_item["date"] = item.get("date")

            items.append(normalized_item)

        return items
