"""
Company API Handler (只读)

职责：
- 加载公司列表
- 不支持创建/更新/删除
"""

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 .sync_node import CompanySyncNode
from schemas.company.company import CompanyResponse


class CompanyApiHandler(BaseApiHandler):
    """公司 API Handler (只读)"""
    
    def __init__(self):
        super().__init__()
        self._node_type = "company"
        self._node_class = CompanySyncNode
        self._schema = CompanyResponse
    
    async def load(self) -> List[SyncNode]:
        """加载公司列表（支持分页）"""
        try:
            nodes = []
            page = 1
            page_size = 1000
            
            while True:
                # 获取一页数据
                companies, total = await api_get_company_list(
                    self.api_client, 
                    page=page, 
                    page_size=page_size
                )
                
                # 没有数据了，退出循环
                if not companies:
                    break
                
                # 转换为节点
                for company_model in companies:
                    company_data = company_model.model_dump()
                    nodes.append(self._create_node(company_data))
                
                # 检查是否还有下一页
                if page * page_size >= total:
                    break
                
                page += 1
            
            return nodes
        except Exception as e:
            print(f"❌ Failed to load companies: {e}")
            import traceback
            traceback.print_exc()
            return []
    
    async def create_all(self, nodes: List[SyncNode]) -> List[TaskResult]:
        """不支持创建"""
        return [
            TaskResult.failed(node_id=node.node_id, error="Company creation not supported")
            for node in nodes
        ]
    
    async def update_all(self, nodes: List[SyncNode]) -> List[TaskResult]:
        """不支持更新"""
        return [
            TaskResult.failed(node_id=node.node_id, error="Company update not supported")
            for node in nodes
        ]
    
    async def delete_all(self, nodes: List[SyncNode]) -> List[TaskResult]:
        """不支持删除"""
        return [
            TaskResult.failed(node_id=node.node_id, error="Company 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:
        return self._create_basic_node(data, depend_ids=[])


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

async def api_get_company_list(client, page: int = 1, page_size: int = 100) -> tuple[List[CompanyResponse], int]:
    """
    获取公司列表 GET /company/list
    
    Args:
        client: API客户端
        page: 页码，从1开始
        page_size: 每页大小
        
    Returns:
        tuple[List[CompanyResponse], int]: (验证过的公司列表, 总数)
    """
    from pydantic import ValidationError
    
    response = await client.request(
        method="GET",
        endpoint="/company/list",
        params={"page": page, "page_size": page_size}
    )
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")
    
    # V2 API 返回格式: {code: 200, data: {list: [...], total: 123, ...}}
    data = response.get("data", {})
    items = data.get("list", [])
    total = data.get("total", 0)
    
    # 验证每个返回项
    validated_items = []
    for item in items:
        try:
            validated_item = CompanyResponse.model_validate(item)
            validated_items.append(validated_item)
        except ValidationError as e:
            print(f"⚠️ Skipping invalid company item: {e}")
            continue
    
    return validated_items, total
