"""
Contract Settlement API Handler

职责：
- 加载合同结算列表（依赖 Project）
- 合同结算创建/更新/删除（批量接口）
"""

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,
    ERROR_PROJECT_ID_NOT_FOUND
)
from .sync_node import ContractSettlementSyncNode
from schemas.contract_settlement.contract_settlement import (
    ContractSettlementResponse,
    ContractSettlementCreate,
    ContractSettlementUpdate,
    ContractSettlementPlanUpdate,
)


class ContractSettlementApiHandler(BaseApiHandler):
    """合同结算 API Handler"""
    
    def __init__(self):
        super().__init__()
        self._node_type = "contract_settlement"
        self._node_class = ContractSettlementSyncNode
        self._schema = ContractSettlementResponse
        self.update_schemas = [ContractSettlementCreate, ContractSettlementUpdate, ContractSettlementPlanUpdate]
    
    async def load(self) -> List[SyncNode]:
        """加载合同结算列表（依赖 Project）"""
        projects = self._collection.filter(node_type="project")
        project_ids = [p.data_id for p in projects if p.data_id]
        
        if not project_ids:
            return []
        
        all_settlements = []
        for project_id in project_ids:
            try:
                settlements = await api_get_contract_settlement_list(self.api_client, project_id)
                for settlement_model in settlements:
                    # 已经过验证的 Pydantic model，转换为 dict
                    settlement_data = settlement_model.model_dump()
                    all_settlements.append(self._create_node(settlement_data))
            except Exception as e:
                print(f"❌ Failed to load settlements for project {project_id}: {e}")
        
        return all_settlements
    
    async def create_all(self, nodes: List[SyncNode]) -> List[TaskResult]:
        """批量创建合同结算"""
        from pydantic import ValidationError
        
        results = []
        for node in nodes:
            data = node.get_data()
            if not data:
                results.append(TaskResult.failed(node_id=node.node_id, error=ERROR_NODE_DATA_NONE))
                continue
            
            project_id = node.context.get("project_id") or data.get("project_id")
            if not project_id:
                results.append(TaskResult.failed(node_id=node.node_id, error=ERROR_PROJECT_ID_NOT_FOUND))
                continue
            
            # 验证并转换为 Pydantic model
            try:
                create_data = {"project_id": project_id, **data}
                create_model = ContractSettlementCreate.model_validate(create_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_settlement(
                    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]:
        """
        批量更新合同结算
        
        支持两种更新类型：
        1. ContractSettlementUpdate - 基础信息更新
        2. ContractSettlementPlanUpdate - 计划信息更新
        
        更新逻辑：
        - 对每种 schema，检查是否有差异
        - 如果有差异，调用对应 API
        """
        from pydantic import ValidationError
        
        results = []
        for node in nodes:
            data = node.get_data()
            if not data:
                results.append(TaskResult.failed(node_id=node.node_id, error=ERROR_NODE_DATA_NONE))
                continue
            
            origin_data = node.get_origin_data() or {}
            biz_id = node.data_id or data.get("id")
            if not biz_id:
                results.append(TaskResult.failed(node_id=node.node_id, error="Missing biz_id for update"))
                continue
            
            node_updated = False
            error = None
            steps_payload = self._get_request_steps(node)
            steps_sent = False
            
            # 1. 基础信息更新 (ContractSettlementUpdate)
            force_steps_update = self._steps_changed(node)
            base_diff = self._get_schema_diff(
                ContractSettlementUpdate,
                data,
                origin_data,
                node.node_id,
                force_full_schema=force_steps_update,
            )
            if base_diff:
                try:
                    update_model = ContractSettlementUpdate.model_validate(data)
                    push_id = self._generate_push_id()
                    await api_update_contract_settlement(
                        self.api_client,
                        update_model,
                        push_id,
                        biz_id,
                        steps=steps_payload if not steps_sent else [],
                    )
                    self._mark_approval_snapshot_synced(node)
                    steps_sent = steps_sent or bool(steps_payload)
                    node_updated = True
                except ValidationError as e:
                    error = f"Validation failed: {e}"
                except Exception as e:
                    error = f"API error: {e}"
            
            # 2. 计划信息更新 (ContractSettlementPlanUpdate)
            plan_diff = self._get_schema_diff(ContractSettlementPlanUpdate, data, origin_data, node.node_id)
            if not error and plan_diff:
                try:
                    plan_model = ContractSettlementPlanUpdate.model_validate(data)
                    push_id = self._generate_push_id()
                    # 使用计划更新专用 API
                    await api_update_settlement_plan(
                        self.api_client,
                        plan_model.model_dump(exclude_unset=True),
                        push_id,
                        biz_id,
                        steps=steps_payload if not steps_sent else [],
                    )
                    self._mark_approval_snapshot_synced(node)
                    steps_sent = steps_sent or bool(steps_payload)
                    node_updated = True
                except ValidationError as e:
                    error = f"Validation failed: {e}"
                except Exception as e:
                    error = f"API error: {e}"
            
            # 汇总结果
            if error:
                results.append(TaskResult.failed(node_id=node.node_id, error=error))
            elif node_updated:
                results.append(TaskResult.success(node_id=node.node_id))
            else:
                # 没有任何字段需要更新
                from ...common.types import SyncAction
                results.append(TaskResult.skipped(node_id=node.node_id, reason="No updatable fields changed"))
        
        return results
    
    async def delete_all(self, nodes: List[SyncNode]) -> List[TaskResult]:
        """批量删除合同结算"""
        results = []
        for node in nodes:
            push_id = self._generate_push_id()
            biz_id = node.data_id
            if not biz_id:
                results.append(TaskResult.failed(node_id=node.node_id, error="Missing biz_id for delete"))
                continue
            
            try:
                await api_delete_contract_settlement(self.api_client, biz_id, push_id)
                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 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"]
        node.context["settlement_id"] = node.data_id
        
        return node


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

async def api_get_settlement(client, settlement_id: str) -> Dict[str, Any]:
    """获取单个合同结算数据 GET /contract_settlement"""
    response = await client.request(
        method="GET",
        endpoint="/contract_settlement",
        params={"settlement_id": settlement_id}
    )
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")
    return response.get("data", {})


async def api_get_contract_settlement_list(client, project_id: str) -> List[ContractSettlementResponse]:
    """
    获取合同结算列表 GET /contract_settlement/list
    
    Args:
        client: API 客户端
        project_id: 项目ID
        
    Returns:
        List[ContractSettlementResponse]: 验证过的结算列表
        
    Raises:
        Exception: API 返回错误或数据验证失败
    """
    from pydantic import ValidationError
    
    response = await client.request(
        method="GET",
        endpoint="/contract_settlement/list",
        params={"project_id": project_id}
    )
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")
    
    items = response.get("data", [])
    
    # 验证每个返回项
    validated_items = []
    for item in items:
        try:
            validated_item = ContractSettlementResponse.model_validate(item)
            validated_items.append(validated_item)
        except ValidationError as e:
            print(f"⚠️ Skipping invalid settlement item: {e}")
            continue
    
    return validated_items


async def api_create_contract_settlement(
    client,
    data: ContractSettlementCreate,
    push_id: str,
    *,
    steps: List[Dict[str, Any]] | None = None,
) -> Dict[str, Any]:
    """
    创建合同结算 POST /contract_settlement/create
    
    Args:
        client: API 客户端
        data: 创建数据（Pydantic model）
        push_id: 推送ID
        biz_id: 业务ID
        
    Returns:
        str: push_id
        
    Raises:
        Exception: API 返回错误
    """
    request_data = {"push_id": push_id, "data": data.model_dump(), "steps": steps or []}
    response = await client.request(method="POST", endpoint="/contract_settlement/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_settlement(
    client,
    data: ContractSettlementUpdate,
    push_id: str,
    biz_id: str,
    *,
    steps: List[Dict[str, Any]] | None = None,
) -> None:
    """
    更新合同结算 PUT /contract_settlement/update
    
    Args:
        client: API 客户端
        data: 更新数据（Pydantic model）
        push_id: 推送ID
        biz_id: 业务ID
        
    Raises:
        Exception: API 返回错误
    """
    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_settlement/update", data=request_data)
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")


async def api_delete_contract_settlement(client, settlement_id: str, push_id: str) -> None:
    """删除合同结算 DELETE /contract_settlement/delete"""
    request_data = {"push_id": push_id, "biz_id": settlement_id}
    response = await client.request(method="DELETE", endpoint="/contract_settlement/delete", data=request_data)
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")


async def api_update_settlement_plan(
    client,
    data: Dict[str, Any],
    push_id: str,
    biz_id: str,
    *,
    steps: List[Dict[str, Any]] | None = None,
) -> None:
    """更新合同结算计划 PUT /contract_settlement/plan"""
    request_data = {"push_id": push_id, "biz_id": biz_id, "data": data, "steps": steps or []}
    response = await client.request(method="PUT", endpoint="/contract_settlement/plan", data=request_data)
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")
