import volcenginesdkecs
import volcenginesdkstorageebs
from volcenginesdkcore.rest import ApiException


class EcsClient:
    """ECS服务客户端"""
    
    def __init__(self):
        self._ecs_api = volcenginesdkecs.ECSApi()
        self._ebs_api = volcenginesdkstorageebs.STORAGEEBSApi()
    
    def list_instances(self, max_results=100):
        """获取ECS实例列表"""
        try:
            req = volcenginesdkecs.DescribeInstancesRequest()
            req.max_results = max_results
            
            response = self._ecs_api.describe_instances(req)
            
            if response and response.instances:
                instances = []
                for inst in response.instances:
                    instances.append({
                        'instance_id': getattr(inst, 'instance_id', 'N/A'),
                        'instance_name': getattr(inst, 'instance_name', 'N/A'),
                        'status': getattr(inst, 'status', 'N/A'),
                        'cpu_count': getattr(inst.cpu_options, 'core_count', 0) if inst.cpu_options else 0,
                        'memory_size': getattr(inst, 'memory_size', 0),
                    })
                
                return {
                    'success': True,
                    'instance_count': len(instances),
                    'instances': instances
                }
            else:
                return {
                    'success': False,
                    'error': '未找到ECS实例'
                }
                
        except ApiException as e:
            return {
                'success': False,
                'error': f'API调用异常: {str(e)}'
            }
        except Exception as e:
            return {
                'success': False,
                'error': f'其他异常: {str(e)}'
            }
    
    def get_total_cpu_and_memory(self, max_requests=50):
        """获取所有ECS实例的CPU和内存总量"""
        req = volcenginesdkecs.DescribeInstancesRequest()
        req.max_results = 100
        total_cpu = 0
        total_mem = 0
        next_token = None
        request_count = 0

        while request_count < max_requests:
            if next_token:
                req.next_token = next_token
            try:
                resp = self._ecs_api.describe_instances(req)
                if not resp or not resp.instances:
                    break

                for inst in resp.instances:
                    cpu = inst.cpu_options
                    cores = cpu.core_count if cpu else 0
                    threads = cpu.threads_per_core if cpu else 0
                    total_cpu += cores * threads
                    mem_mib = inst.memory_size or 0
                    total_mem += mem_mib / 1024

                next_token = resp.next_token
                request_count += 1

                if not next_token:
                    break
            except ApiException as e:
                return {
                    'success': False,
                    'error': f'ECS API调用异常: {str(e)}'
                }
            except Exception as e:
                return {
                    'success': False,
                    'error': f'ECS未知错误: {str(e)}'
                }

        return {
            'success': True,
            'total_cpu': total_cpu,
            'total_memory': round(total_mem, 2)
        }
    
    def get_total_disk(self, max_pages=100):
        """获取所有EBS卷的磁盘总量"""
        req = volcenginesdkstorageebs.DescribeVolumesRequest()
        req.page_size = 100
        req.page_number = 1
        total_disk = 0

        while req.page_number <= max_pages:
            try:
                resp = self._ebs_api.describe_volumes(req)
                if not resp or not resp.volumes:
                    break

                for vol in resp.volumes:
                    total_disk += int(vol.size or 0)

                if len(resp.volumes) < req.page_size:
                    break

                req.page_number += 1

            except ApiException as e:
                return {
                    'success': False,
                    'error': f'EBS API调用异常: {str(e)}'
                }
            except Exception as e:
                return {
                    'success': False,
                    'error': f'EBS未知错误: {str(e)}'
                }

        return {
            'success': True,
            'total_disk': total_disk
        }
    
    def get_resource_summary(self):
        """获取ECS资源汇总信息"""
        try:
            # 获取CPU和内存
            cpu_mem_result = self.get_total_cpu_and_memory()
            if not cpu_mem_result['success']:
                return cpu_mem_result
            
            # 获取磁盘
            disk_result = self.get_total_disk()
            if not disk_result['success']:
                return disk_result
            
            return {
                'success': True,
                'cpu': cpu_mem_result['total_cpu'],
                'memory': cpu_mem_result['total_memory'],
                'disk': disk_result['total_disk']
            }
            
        except Exception as e:
            return {
                'success': False,
                'error': f'资源统计出错: {str(e)}'
            }
