"""
LAR Change (移民变更) API Handler

职责：
- 创建和更新移民变更记录（依赖 Project）

实现的接口：
POST:
- /lar/change - 创建移民变更
PUT:
- /lar/change - 更新移民变更
"""

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 LarChangeSyncNode
from schemas.project_extensions.lar import (
    LarChangeDetailSchema,
    LarChangeCreateSchema,
    LarChangeUpdateSchema
)


class LarChangeApiHandler(BaseApiHandler):
    """移民变更 API Handler"""
    
    def __init__(self):
        super().__init__()
        self._node_type = "lar_change"
        self._node_class = LarChangeSyncNode
        self._schema = LarChangeDetailSchema
    
    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 []
        
        # 移民变更通常需要单独查询，这里暂时返回空
        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 = LarChangeCreateSchema.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_lar_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,
                LarChangeUpdateSchema,
                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 = LarChangeUpdateSchema.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_lar_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="LAR 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"]
        
        return node


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

async def api_create_lar_change(
    client,
    data: LarChangeCreateSchema,
    push_id: str,
    *,
    steps: List[Dict[str, Any]] | None = None,
) -> Dict[str, Any]:
    """
    POST /lar/change - 创建移民变更
    
    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="/lar/change", data=request_data)
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")
    return response


async def api_update_lar_change(
    client,
    data: LarChangeUpdateSchema,
    push_id: str,
    biz_id: str,
    *,
    steps: List[Dict[str, Any]] | None = None,
) -> None:
    """
    PUT /lar/change - 更新移民变更
    
    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="/lar/change", data=request_data)
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")
