"""
Contract Change (合同变更) API Handler

职责：
- 创建和更新合同变更记录（依赖 Project 和 Contract）

实现的接口：
POST:
- /contract_change/create - 创建合同变更
PUT:
- /contract_change/update - 更新合同变更
"""

from typing import List, Dict, Any
from ...datasource.api.handler import BaseApiHandler
from ...datasource.task_result import TaskResult
from ...common.sync_node import SyncNode
from ...datasource.api.errors import ERROR_NODE_DATA_NONE, ERROR_VALIDATION_FAILED
from .sync_node import ContractChangeSyncNode
from schemas.project_extensions.contract_change import ContractChangeResponse, PostContractChange, CreateContractChange


class ContractChangeApiHandler(BaseApiHandler):
    """合同变更 API Handler"""
    
    def __init__(self):
        super().__init__()
        self._node_type = "contract_change"
        self._node_class = ContractChangeSyncNode
        # TODO: ContractChangeResponse schema in schemas/project_extensions/contract_change.py is missing 'project_id'
        self._schema = ContractChangeResponse
    
    async def load(self) -> List[SyncNode]:
        """加载合同变更数据"""
        return []
    
    async def create_all(self, nodes: List[SyncNode]) -> List[TaskResult]:
        """批量创建合同变更"""
        from pydantic import ValidationError
        
        results = []
        for node in nodes:
            node_data = node.get_data()
            if node_data is None:
                results.append(TaskResult.failed(node_id=node.node_id, error=ERROR_NODE_DATA_NONE))
                continue
            
            # 验证并转换为 Pydantic model
            try:
                create_model = CreateContractChange.model_validate(node_data)
            except ValidationError as e:
                results.append(TaskResult.failed(node_id=node.node_id, error=f"{ERROR_VALIDATION_FAILED}: {e}"))
                continue
            
            push_id = self._generate_push_id()
            
            try:
                response = await api_create_contract_change(
                    self.api_client,
                    create_model,
                    push_id,
                    steps=self._get_request_steps(node),
                )
                if self.poll_mode == "sync":
                    created_id = self._extract_created_id_from_response(response)
                    if not created_id:
                        results.append(
                            TaskResult.failed(
                                node_id=node.node_id,
                                error="Missing created_id in create response"
                            )
                        )
                        continue
                    results.append(TaskResult.success(node_id=node.node_id, data_id=created_id))
                else:
                    results.append(TaskResult.in_progress(node_id=node.node_id, task_id=push_id))
            except Exception as e:
                results.append(TaskResult.failed(node_id=node.node_id, error=str(e)))
        
        return results
    
    async def update_all(self, nodes: List[SyncNode]) -> List[TaskResult]:
        """批量更新合同变更"""
        from pydantic import ValidationError
        
        results = []
        for node in nodes:
            node_data = node.get_data()
            if node_data is None:
                error_msg = node.error or "Node data is missing or invalid"
                results.append(TaskResult.failed(node_id=node.node_id, error=f"Cannot update: {error_msg}"))
                continue
                
            origin_data = node.get_origin_data() or {}
            force_steps_update = self._steps_changed(node)
            update_data = self._filter_update_data(
                node_data,
                origin_data,
                PostContractChange,
                force_full_schema=force_steps_update,
            )
            if not update_data:
                from ...common.types import SyncAction
                results.append(TaskResult.skipped(node_id=node.node_id, reason="No updatable fields changed"))
                continue
            
            # 验证并转换为 Pydantic model
            try:
                update_model = PostContractChange.model_validate(update_data)
            except ValidationError as e:
                results.append(TaskResult.failed(node_id=node.node_id, error=f"{ERROR_VALIDATION_FAILED}: {e}"))
                continue
            
            push_id = self._generate_push_id()
            biz_id = node.data_id or update_model.id
            if not biz_id:
                results.append(TaskResult.failed(node_id=node.node_id, error="Missing biz_id for update"))
                continue
            
            try:
                await api_update_contract_change(
                    self.api_client,
                    update_model,
                    push_id,
                    biz_id,
                    steps=self._get_request_steps(node),
                )
                self._mark_approval_snapshot_synced(node)
                results.append(TaskResult.success(node_id=node.node_id))
            except Exception as e:
                results.append(TaskResult.failed(node_id=node.node_id, error=str(e)))
        
        return results
    
    async def delete_all(self, nodes: List[SyncNode]) -> List[TaskResult]:
        """不支持删除"""
        return [
            TaskResult.failed(node_id=node.node_id, error="Contract change deletion not supported")
            for node in nodes
        ]
    
    async def poll_tasks(self, task_ids: List[str]) -> Dict[str, TaskResult]:
        """轮询异步任务状态"""
        return await super().poll_tasks(task_ids)
    
    def _create_node(self, data: Dict[str, Any]) -> SyncNode:
        node = self._create_basic_node(data, depend_ids=[])
        
        if data.get("project_id"):
            node.context["project_id"] = data["project_id"]
        if data.get("contract_id"):
            node.context["contract_id"] = data["contract_id"]
        
        return node


# ========== 静态 API 函数 ==========

async def api_create_contract_change(
    client,
    data: CreateContractChange,
    push_id: str,
    *,
    steps: List[Dict[str, Any]] | None = None,
) -> Dict[str, Any]:
    """
    POST /contract_change/create - 创建合同变更
    
    Args:
        client: API 客户端
        data: 创建数据（Pydantic model）
        push_id: 推送ID
        biz_id: 业务ID
    """
    request_data = {"push_id": push_id, "data": data.model_dump(), "steps": steps or []}
    response = await client.request(method="POST", endpoint="/contract_change/create", data=request_data)
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")
    return response


async def api_update_contract_change(
    client,
    data: PostContractChange,
    push_id: str,
    biz_id: str,
    *,
    steps: List[Dict[str, Any]] | None = None,
) -> None:
    """
    PUT /contract_change/update - 更新合同变更
    
    Args:
        client: API 客户端
        data: 更新数据（Pydantic model）
        push_id: 推送ID
        biz_id: 业务ID
    """
    request_data = {"push_id": push_id, "biz_id": biz_id, "data": data.model_dump(exclude_unset=True), "steps": steps or []}
    response = await client.request(method="PUT", endpoint="/contract_change/update", data=request_data)
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")
