#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
SARM SDK 漏洞 API

提供漏洞相关的API操作。
"""

from typing import List, Dict, Any, Optional, TYPE_CHECKING
from ..models.response import BatchOperationResult
from ..exceptions import SARMValidationError

if TYPE_CHECKING:
    from ..client import SARMClient


class VulnerabilityAPI:
    """漏洞API类"""
    
    def __init__(self, client: 'SARMClient'):
        self.client = client
    
    def create_batch(
        self,
        vulnerabilities: List[Dict[str, Any]],
        execute_release: bool = False
    ) -> BatchOperationResult:
        """
        批量创建漏洞
        
        Args:
            vulnerabilities: 漏洞数据列表
            execute_release: 是否直接发布
            
        Returns:
            批量操作结果
        """
        if not vulnerabilities:
            raise SARMValidationError("漏洞列表不能为空")
        
        if len(vulnerabilities) > 1000:
            raise SARMValidationError("单次批量操作不能超过1000条记录")
        
        # 发送请求
        response = self.client.post(
            '/api/vuln/create',
            data=vulnerabilities,
            execute_release=execute_release
        )
        
        # 处理批量操作结果
        if isinstance(response, dict) and 'code' in response and 'data' in response:
            from ..models.response import BatchOperationItem
            
            # 如果有详细的响应数据
            if isinstance(response.get('data'), list):
                items = [
                    BatchOperationItem(
                        unique_id=item.get('unique_id', ''),
                        name=item.get('title', ''),
                        success=item.get('success', False),
                        msg=item.get('msg', '')
                    )
                    for item in response['data']
                ]
            else:
                # 简单成功响应
                success = response.get('code') == 200
                items = [
                    BatchOperationItem(
                        unique_id=vuln.get('vuln_unique_id', f"vuln_{i}"),
                        name=vuln.get('title', ''),
                        success=success,
                        msg="创建成功" if success else "创建失败"
                    )
                    for i, vuln in enumerate(vulnerabilities)
                ]
            
            return BatchOperationResult(
                data=items,
                code=response.get('code', 200)
            )
        
        return BatchOperationResult(**response)
    
    def create(self, vulnerability: Dict[str, Any], execute_release: bool = False) -> BatchOperationResult:
        """创建单个漏洞"""
        return self.create_batch([vulnerability], execute_release=execute_release)
    
    def update(self, vulnerability_data: Dict[str, Any]) -> Dict[str, Any]:
        """更新漏洞信息"""
        if 'vuln_unique_id' not in vulnerability_data:
            raise SARMValidationError("更新漏洞时必须提供 vuln_unique_id")
        
        response = self.client.post('/api/vuln/update', data=vulnerability_data)
        return response
    
    def get_list(
        self,
        page: int = 1,
        limit: int = 50,
        severity: Optional[str] = None,
        status: Optional[str] = None
    ) -> Dict[str, Any]:
        """获取漏洞列表"""
        params = {"page": page, "limit": limit}
        if severity:
            params["severity"] = severity
        if status:
            params["status"] = status
        
        response = self.client.get('/api/vuln/', params=params)
        return response 