"""
Personnel Detail API Handler

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

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_ID_NOT_FOUND
from .sync_node import PersonnelDetailSyncNode
from schemas.power.power_detail import PowerDetail, PowerDetailCreate, PowerDetailUpdate


class PersonnelDetailApiHandler(BaseApiHandler):
    """人员明细 API Handler"""
    
    def __init__(self):
        super().__init__()
        self._node_type = "personnel_detail"
        self._node_class = PersonnelDetailSyncNode
        self._schema = PowerDetail
        self.update_schemas = [PowerDetailCreate, PowerDetailUpdate]
    
    async def load(self) -> List[SyncNode]:
        """加载人员明细列表（依赖 Personnel）"""
        personnel_list = self._collection.filter(node_type="personnel")
        personnel_ids = [p.data_id for p in personnel_list if p.data_id]
        
        if not personnel_ids:
            return []
        
        all_details = []
        for personnel_id in personnel_ids:
            try:
                details = await api_get_personnel_detail_list(self.api_client, personnel_id)
                for detail in details:
                    validated = PowerDetail.model_validate(detail)
                    all_details.append(self._create_node(validated.model_dump()))
            except Exception as e:
                print(f"❌ Failed to load personnel details for {personnel_id}: {e}")
        
        return all_details
    
    async def create_all(self, nodes: List[SyncNode]) -> List[TaskResult]:
        """批量创建人员明细"""
        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获取personnel_id
            personnel_id = data.get("parent_id")
            if not personnel_id:
                results.append(TaskResult.failed(node_id=node.node_id, error=ERROR_ID_NOT_FOUND))
                continue
            
            push_id = self._generate_push_id()
            
            try:
                request_data = {"personnel_id": personnel_id, **data}
                PowerDetailCreate.model_validate(request_data)
                response = await api_create_personnel_detail(
                    self.api_client,
                    request_data,
                    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]:
        """
        批量更新人员明细
        
        按 personnel_id 分组，每组使用同一个 push_id 批量提交
        """
        from pydantic import ValidationError
        from collections import defaultdict
        
        results = []
        
        # 按 personnel_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(
                PowerDetailUpdate,
                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
            
            # 获取 personnel_id（parent_id）
            personnel_id = data.get("parent_id") or node.context.get("personnel_id")
            if not personnel_id:
                results.append(TaskResult.failed(node_id=node.node_id, error="Missing personnel_id (parent_id)"))
                continue
            
            # 需要完整的 schema 数据（包括必填字段）
            update_data = self._filter_update_data(
                data,
                origin_data,
                PowerDetailUpdate,
                force_full_schema=force_steps_update,
            )
            
            # 验证并转换为 Pydantic model
            try:
                update_model = PowerDetailUpdate.model_validate(update_data)
                groups[personnel_id].append((node, update_model))
            except ValidationError as e:
                results.append(TaskResult.failed(node_id=node.node_id, error=f"Validation failed: {e}"))
        
        # 逐组批量更新
        for personnel_id, group_items in groups.items():
            push_id = self._generate_push_id()
            
            # 准备批量数据
            detail_list = [model.model_dump(exclude_unset=True) for node, model in group_items]
            steps = self._get_request_steps(group_items[0][0]) if group_items else []
            
            # 使用 parent_id（personnel_id）作为 biz_id
            biz_id = personnel_id
            
            try:
                # 批量调用 API
                await api_update_personnel_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)
                    results.append(TaskResult.success(node_id=node.node_id, push_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_personnel_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("personnel_id"):
            node.context["personnel_id"] = data["personnel_id"]
        
        return node


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

async def api_get_personnel_detail_list(client, personnel_id: str) -> List[Dict[str, Any]]:
    response = await client.request(
        method="GET",
        endpoint="/personnel/detail/list",
        params={"personnel_id": personnel_id}
    )
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")
    return response.get("data", [])


async def api_create_personnel_detail(
    client,
    data: Dict[str, Any],
    push_id: str,
    *,
    steps: List[Dict[str, Any]] | None = None,
) -> Dict[str, Any]:
    request_data = {"push_id": push_id, "data": data, "steps": steps or []}
    response = await client.request(method="POST", endpoint="/personnel/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_personnel_detail(
    client,
    data: Dict[str, Any],
    push_id: str,
    biz_id: str,
    *,
    steps: List[Dict[str, Any]] | None = None,
) -> None:
    request_data = {"push_id": push_id, "biz_id": biz_id, "data": data, "steps": steps or []}
    response = await client.request(method="PUT", endpoint="/personnel/detail/update", data=request_data)
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")


async def api_delete_personnel_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="/personnel/detail/delete", data=request_data)
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")
