"""
Construction Task Detail API Handler (V2)

职责：
- 加载施工明细列表（依赖 ConstructionTask）
- 施工明细创建/更新/删除（批量接口）
"""

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_ID_NOT_FOUND
from .sync_node import ConstructionTaskDetailSyncNode
from schemas.construction.construction_detail import (
    ConstructionDetailResponse,
    ConstructionDetailCreate,
    ConstructionDetailUpdate
)


class ConstructionTaskDetailApiHandler(BaseApiHandler):
    """施工明细 API Handler"""
    
    def __init__(self):
        super().__init__()
        self._node_type = "construction_task_detail"
        self._node_class = ConstructionTaskDetailSyncNode
        self._schema = ConstructionDetailResponse
        self.update_schemas = [ConstructionDetailCreate, ConstructionDetailUpdate]
    
    async def load(self) -> List[SyncNode]:
        """加载施工明细列表（依赖 ConstructionTask）"""
        tasks = self._collection.filter(node_type="construction_task")
        task_ids = [t.data_id for t in tasks if t.data_id]
        
        if not task_ids:
            return []
        
        all_details = []
        for task_id in task_ids:
            try:
                details = await api_get_construction_task_detail_list(self.api_client, task_id)
                for detail_model in details:
                    # 已验证的 Pydantic model，转换为 dict
                    detail_data = detail_model.model_dump()
                    all_details.append(self._create_node(detail_data))
            except Exception as e:
                print(f"❌ Failed to load construction details for task {task_id}: {e}")
        
        return all_details
    
    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
            
            # 从data的parent_id获取task_id
            task_id = data.get("parent_id")
            if not task_id:
                results.append(TaskResult.failed(node_id=node.node_id, error=ERROR_ID_NOT_FOUND))
                continue
            
            # 验证并转换为 Pydantic model
            try:
                create_data = {"task_id": task_id, **data}
                create_model = ConstructionDetailCreate.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_construction_task_detail(
                    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]:
        """
        批量更新施工明细
        
        按 task_id 分组，每组使用同一个 push_id 批量提交
        """
        from pydantic import ValidationError
        from collections import defaultdict
        
        results = []
        
        # 按 task_id 分组
        groups: Dict[str, List[tuple[SyncNode, Dict[str, Any]]]] = defaultdict(list)
        
        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 {}
            
            # 使用 _get_schema_diff 检查差异并打印日志
            force_steps_update = self._steps_changed(node)
            diff_fields = self._get_schema_diff(
                ConstructionDetailUpdate,
                data,
                origin_data,
                node.node_id,
                force_full_schema=force_steps_update,
            )
            if not diff_fields:
                from ...common.types import SyncAction
                results.append(TaskResult.skipped(node_id=node.node_id, reason="No updatable fields changed"))
                continue
            
            # 获取 task_id（parent_id）
            task_id = data.get("parent_id") or node.context.get("task_id")
            if not task_id:
                results.append(TaskResult.failed(node_id=node.node_id, error="Missing task_id (parent_id)"))
                continue
            
            # 需要完整的 schema 数据（包括必填字段）
            update_data = self._filter_update_data(
                data,
                origin_data,
                ConstructionDetailUpdate,
                force_full_schema=force_steps_update,
            )
            
            # 验证并转换为 Pydantic model
            try:
                update_model = ConstructionDetailUpdate.model_validate(update_data)
                groups[task_id].append((node, update_model))
            except ValidationError as e:
                results.append(TaskResult.failed(node_id=node.node_id, error=f"{ERROR_VALIDATION_FAILED}: {e}"))
        
        # 逐组批量更新
        for task_id, group_items in groups.items():
            push_id = self._generate_push_id()
            
            # 准备批量数据
            detail_list = [model.model_dump(mode='json', exclude_unset=True) for node, model in group_items]
            steps = self._get_request_steps(group_items[0][0]) if group_items else []
            
            # 使用 parent_id（task_id）作为 biz_id
            biz_id = task_id
            
            try:
                # 批量调用 API
                await api_update_construction_task_detail(
                    self.api_client,
                    {"detail_list": detail_list},
                    push_id,
                    biz_id,
                    steps=steps,
                )
                # 整组成功
                for node, _ in group_items:
                    self._mark_approval_snapshot_synced(node)
                    if self.poll_mode == "sync":
                        results.append(TaskResult.success(node_id=node.node_id))
                    else:
                        results.append(TaskResult.in_progress(node_id=node.node_id, task_id=push_id))
            except Exception as e:
                # 整组失败
                error_msg = str(e)
                for node, _ in group_items:
                    results.append(TaskResult.failed(node_id=node.node_id, error=error_msg))
        
        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_construction_task_detail(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("task_id"):
            node.context["task_id"] = data["task_id"]
        
        return node


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

async def api_get_construction_task_detail_list(client, task_id: str) -> List[ConstructionDetailResponse]:
    """
    获取施工明细列表 GET /construction_task_detail/list
    
    Args:
        client: API 客户端
        task_id: 施工任务ID
        
    Returns:
        List[ConstructionDetailResponse]: 验证过的明细列表
    """
    from pydantic import ValidationError
    
    response = await client.request(
        method="GET",
        endpoint="/construction/detail/list",
        params={"task_id": task_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 = ConstructionDetailResponse.model_validate(item)
            validated_items.append(validated_item)
        except ValidationError as e:
            print(f"⚠️ Skipping invalid detail item: {e}")
            continue
    
    return validated_items


async def api_create_construction_task_detail(
    client,
    data: ConstructionDetailCreate,
    push_id: str,
    *,
    steps: List[Dict[str, Any]] | None = None,
) -> Dict[str, Any]:
    """
    创建施工明细 POST /construction/detail/create
    
    Args:
        client: API 客户端
        data: 创建数据（Pydantic model）
        push_id: 推送ID
        biz_id: 业务ID
    """
    request_data = {"push_id": push_id, "data": data.model_dump(mode='json'), "steps": steps or []}
    response = await client.request(method="POST", endpoint="/construction/detail/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_construction_task_detail(
    client,
    data: Dict[str, Any],
    push_id: str,
    biz_id: str,
    *,
    steps: List[Dict[str, Any]] | None = None,
) -> None:
    """
    更新施工明细 PUT /construction/detail/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, "steps": steps or []}
    response = await client.request(method="PUT", endpoint="/construction/detail/update", data=request_data)
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")


async def api_delete_construction_task_detail(client, detail_id: str, push_id: str) -> None:
    request_data = {"push_id": push_id, "biz_id": detail_id}
    response = await client.request(method="DELETE", endpoint="/construction/detail/delete", data=request_data)
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")
