"""
Production (投产节点) API Handler

职责：
- 更新项目投产节点数据
- 不支持创建和删除（投产节点随项目自动生成）

实现的接口：
PUT:
- /production - 更新投产节点数据
"""

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_VALIDATION_FAILED
from .sync_node import ProductionSyncNode
from schemas.project_extensions.production import ProductionDetail, PostProduction


class ProductionApiHandler(BaseApiHandler):
    """投产节点 API Handler"""
    
    def __init__(self):
        super().__init__()
        self._node_type = "production"
        self._node_class = ProductionSyncNode
        self._schema = ProductionDetail
        self.update_schemas = [PostProduction]
    
    async def load(self) -> List[SyncNode]:
        """加载投产节点数据（从 project all_info 中提取）"""
        from ..project.api_handler import ProjectApiHandler
        
        # 获取已加载的项目
        projects = self._collection.filter(node_type="project")
        if not projects:
            print("⚠️ No projects found, skipping production load")
            return []
        
        nodes = []
        for project in projects:
            project_id = project.data_id
            
            try:
                # 从 project context 或缓存获取 all_info
                all_info = project.context.get("all_info")
                if not all_info:
                    all_info = await ProjectApiHandler.get_all_info(
                        self.api_client,
                        project_id
                    )
                
                # 提取 production_list
                production_list = all_info.get("production_list", [])
                print(f"  Project {project_id}: {len(production_list)} productions")
                
                for prod_data in production_list:
                    # 验证数据
                    try:
                        validated = self._schema.model_validate(prod_data)
                        node = self._create_node(validated.model_dump())
                        node.context["project_id"] = project_id
                        nodes.append(node)
                    except Exception as e:
                        print(f"⚠️ Skipping invalid production: {e}")
                        continue
                        
            except Exception as e:
                print(f"❌ Failed to load productions for project {project_id}: {e}")
                continue
        
        return nodes
    
    async def create_all(self, nodes: List[SyncNode]) -> List[TaskResult]:
        """不支持创建"""
        return [
            TaskResult.failed(node_id=node.node_id, error="Production creation not supported (auto-generated with project)")
            for node in nodes
        ]
    
    async def update_all(self, nodes: List[SyncNode]) -> List[TaskResult]:
        """批量更新投产节点数据"""
        from pydantic import ValidationError
        
        results = []
        
        for node in nodes:
            # 获取节点数据 (仅限 schema 内字段)
            node_data = node.get_data()
            if not node_data:
                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
            
            # 获取来自 API load 的原始数据进行对比
            origin_data = node.get_origin_data() or {}
            
            # 获取过滤后的更新数据
            force_steps_update = self._steps_changed(node)
            update_data = self.build_update_request_data(
                node_data,
                origin_data,
                PostProduction,
                force_full_schema=force_steps_update,
            )
            
            if not update_data:
                reason = f"No physical diff found for production {node.data_id} despite strategy update request (Normalization Discrepancy)."
                print(f"  [WARNING] [production] {reason}")
                results.append(TaskResult.skipped(node_id=node.node_id, reason=reason))
                continue
            
            # 验证并转换为 Pydantic model
            try:
                update_model = PostProduction.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()
            update_model_data = update_model.model_dump()
            biz_id = node.data_id or update_model_data.get("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_production(
                    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="Production 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_update_production(
    client,
    data: PostProduction,
    push_id: str,
    biz_id: str,
    *,
    steps: List[Dict[str, Any]] | None = None,
) -> None:
    """
    PUT /production - 更新投产节点数据
    
    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="/production_nodes", data=request_data)
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")
