import os
import volcenginesdkcore
import volcenginesdknatgateway
from volcenginesdkcore.rest import ApiException

class VolcCloudNAT:
    def __init__(self):
        self.ak = os.getenv("VOLC_ACCESS_KEY")
        self.sk = os.getenv("VOLC_SECRET_KEY")
        self.region = os.getenv("VOLC_REGION", "cn-beijing")
        if not self.ak or not self.sk:
            raise EnvironmentError("请设置 VOLC_ACCESS_KEY 和 VOLC_SECRET_KEY 环境变量。")
        self.init_volc_config()
        self.nat_api = volcenginesdknatgateway.NATGATEWAYApi()

    def init_volc_config(self):
        config = volcenginesdkcore.Configuration()
        config.ak = self.ak
        config.sk = self.sk
        config.region = self.region
        volcenginesdkcore.Configuration.set_default(config)

    def get_nat_eips(self):
        try:
            req = volcenginesdknatgateway.DescribeNatGatewaysRequest()
            resp = self.nat_api.describe_nat_gateways(req)
            result = []

            # 正确读取字段：resp.nat_gateways
            for nat in resp.nat_gateways:
                nat_id = nat.nat_gateway_id
                nat_name = nat.nat_gateway_name
                eip_addresses = [
                    eip.eip_address for eip in getattr(nat, "eip_addresses", [])
                ]
                result.append({
                    "nat_id": nat_id,
                    "nat_name": nat_name,
                    "eips": eip_addresses,
                    "cloud": "Volc"
                })

            return result

        except ApiException as e:
            print(f"[火山云NAT] 请求出错: {e}")
            return []
