"""
User API Handler (只读)

职责：
- 加载用户列表
- 不支持创建/更新/删除

实现的接口：
GET:
- /user/list - 获取用户列表
"""

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 UserSyncNode
from schemas.user.user import UserListDetailItem


class UserApiHandler(BaseApiHandler):
    """用户 API Handler (只读)"""
    
    def __init__(self):
        super().__init__()
        self._node_type = "user"
        self._node_class = UserSyncNode
        self._schema = UserListDetailItem
    
    async def load(self) -> List[SyncNode]:
        """加载用户列表（支持分页）"""
        try:
            nodes = []
            page = 1
            page_size = 100
            
            while True:
                # 获取一页数据
                users, total = await api_get_user_list(
                    self.api_client,
                    page=page,
                    page_size=page_size
                )
                
                # 没有数据了，退出循环
                if not users:
                    break
                
                # 转换为节点
                for user_model in users:
                    user_data = user_model.model_dump()
                    nodes.append(self._create_node(user_data))
                
                # 检查是否还有下一页
                if page * page_size >= total:
                    break
                
                page += 1
            
            return nodes
        except Exception as e:
            print(f"❌ Failed to load users: {e}")
            return []
    
    async def create_all(self, nodes: List[SyncNode]) -> List[TaskResult]:
        """不支持创建"""
        return [
            TaskResult.failed(node_id=node.node_id, error="User 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="User 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="User 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_user_list(client, page: int = 1, page_size: int = 100) -> tuple[List[UserListDetailItem], int]:
    """
    GET /user/list - 获取用户列表
    
    Args:
        client: API客户端
        page: 页码，从1开始
        page_size: 每页大小
        
    Returns:
        tuple[List[UserListDetailItem], int]: (验证过的用户列表, 总数)
    """
    from pydantic import ValidationError
    
    response = await client.request(
        method="GET",
        endpoint="/user/list",
        params={"page": page, "page_size": page_size}
    )
    if response.get("code") != 200:
        raise Exception(f"API error: {response.get('message', 'Unknown error')}")
    
    data = response.get("data", {})
    items = data.get("list", [])
    total = data.get("total", 0)
    
    # 验证每个返回项
    validated_items = []
    for item in items:
        try:
            validated_item = UserListDetailItem.model_validate(item)
            validated_items.append(validated_item)
        except ValidationError as e:
            print(f"⚠️ Skipping invalid user item: {e}")
            continue
    
    return validated_items, total
