from __future__ import annotations

from typing import Any

from common.debug_billing import is_on_demand_debug_enabled
from common.shared import (
    BANDWIDTH_CHARGE_MODE,
    BANDWIDTH_SIZE,
    BILLING_AUTO_PAY,
    BILLING_AUTO_RENEW,
    BILLING_MODE,
    BILLING_PERIOD_NUM,
    BILLING_PERIOD_TYPE,
    EIP_TYPE,
    ROOT_VOLUME_CANDIDATES,
    ROOT_VOLUME_SIZE,
)
from HUAWEI.flavor_helpers import flavor_mode_label
from HUAWEI.network_plan import aux_private_ips, expected_public_ip_count, standard_private_ips, virtual_private_ips


def purchase_config_snapshot(
    *,
    plan: Any,
    pair: Any,
    flavor_mode: str,
    server_name: str,
    availability_zone: str,
    flavor_id: str,
    image_id: str,
    image_name: str,
    vpc_id: str,
    subnet_id: str,
    subnet_network_id: str,
    security_group_id: str,
    root_volume_type: str,
    root_volume_label: str,
) -> str:
    """生成华为云自动购买前的配置快照，方便日志追踪和人工核对。"""
    standard_ips = standard_private_ips(plan)
    virtual_ips = virtual_private_ips(plan)
    aux_ips = aux_private_ips(plan)
    if is_on_demand_debug_enabled("huawei"):
        billing_line = "计费: ECS=postPaid 按需计费调试模式，仅供测试"
    else:
        billing_line = (
            f"计费: ECS={BILLING_MODE} {BILLING_PERIOD_NUM}{BILLING_PERIOD_TYPE} "
            f"autoRenew={BILLING_AUTO_RENEW} autoPay={BILLING_AUTO_PAY}"
        )
    return "\n".join(
        [
            "自动购买配置快照:",
            f"地区: {plan.label} key={plan.key} region={pair.region} project_id={pair.project_id}",
            f"规格模式: {flavor_mode_label(flavor_mode)} flavor={flavor_id} availability_zone={availability_zone or '自动AZ'}",
            f"镜像: {image_name} ({image_id})",
            f"ECS名称: {server_name}",
            billing_line,
            f"系统盘: {root_volume_label}({root_volume_type}) {ROOT_VOLUME_SIZE}GiB",
            f"网络: vpc={vpc_id} subnet={subnet_id} network={subnet_network_id} security_group={security_group_id}",
            f"标准私网IP: {','.join(standard_ips)}",
            f"虚拟IP计划: {','.join(virtual_ips) if virtual_ips else '无'}",
            f"辅助私网IP计划: {','.join(aux_ips) if aux_ips else '无'}",
            (
                f"EIP计划: {expected_public_ip_count(plan)}条 type={EIP_TYPE} "
                f"bandwidth={BANDWIDTH_SIZE}M charge={BANDWIDTH_CHARGE_MODE}"
            ),
            "安全组规则: IPv4 入方向 TCP/UDP 1-52、54-65535，GRE、ICMP 全部，源地址 0.0.0.0/0",
        ]
    )


def volume_type_label(volume_type: str) -> str:
    """把华为云系统盘类型转换成用户可读的中文标签。"""
    for item_type, label in ROOT_VOLUME_CANDIDATES:
        if item_type == volume_type:
            return label
    return volume_type
