import concurrent.futures
import ctypes
import hashlib
import hmac
import ipaddress
import json
import os
import random
import re
import socket
import subprocess
import sys
import threading
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Set, Tuple

from common.package_metadata_fallbacks import ensure_package_metadata_fallbacks

ensure_package_metadata_fallbacks()

import tkinter as tk
import tkinter.font as tkfont
from tkinter import messagebox, ttk

import paramiko

from common.codec_fallbacks import ensure_idna_codec
from common.models import CloudApiError, ProjectPair, RegionBuildResult, RegionPlan
from common.runtime_paths import ASSETS_DIR, PROJECT_ROOT, _runtime_base_dir, bundled_dir, cloud_log_dir, resource_path

ensure_idna_codec()


APP_TITLE = "多云管理"
APP_BUILD_VERSION = "v6.18.59"
APP_VERSION = "6.18.59"
APP_ICON_FILENAME = "app_icon_v85.ico"
SCRIPT_FILENAME = "fifteenhuawei.sh"
APP_LOG_DIR = str(cloud_log_dir("common"))
DESTRUCTIVE_CONFIRM_TEXT = "确认执行退订/删除/释放/重装会影响资源且可能无法恢复"

ALGORITHM = "SDK-HMAC-SHA256"
IAM_ENDPOINT = "https://iam.myhuaweicloud.com"
BSS_ENDPOINT = "https://bss.myhuaweicloud.com"
SUBSCRIPTION_QUERY_PATHS = [
    "/v2/orders/suscriptions/resources/query",
    "/v2/orders/subscriptions/resources/query",
]
SUBSCRIPTION_UNSUBSCRIBE_PATH = "/v2/orders/subscriptions/resources/unsubscribe"
CHECKED = "✓"
UNCHECKED = "□"
APP_BG = "#f3f3f3"
PANEL_BG = "#f3f3f3"
CONTENT_BG = "#f3f3f3"
TEXT_BG = "#ffffff"
TEXT_FG = "#000000"
MUTED_FG = "#666666"
BORDER_COLOR = "#d0d5dd"
TABLE_BORDER_COLOR = "#d0d5dd"
TABLE_ALT_BG = "#f8f8f8"
TABLE_GROUP_BG = "#eeeeee"
TABLE_HEADER_BG = "#f0f0f0"
SCROLL_TROUGH = "#f3f3f3"
SCROLL_THUMB = "#c8c8c8"
SCROLL_ACTIVE = "#a8a8a8"
ACCENT_BG = "#f2f4f7"
BUTTON_BG = "#ffffff"
BUTTON_ACTIVE_BG = "#f2f4f7"
TAB_PIXEL_WIDTH = 121
TAB_PIXEL_HEIGHT = 55

FLAVOR_ID = "x1.2u.2g"
FLAVOR_DESC = "通用计算型 | x1.2u.2g | 2vCPUs | 2GiB"
FLAVOR_MODE_FIXED = "fixed"
FLAVOR_MODE_LOWEST = "lowest"
FLAVOR_MODE_WAWACLOUD_LOW = "wawacloud_low"
FLAVOR_MODE_WAWACLOUD_20 = "wawacloud_20"
TWENTY_CONFIG_FLAVORS = ("s7.small.1",)
HUAWEI_AUTOBUY_SOURCE_MODES = {
    FLAVOR_MODE_FIXED: "华为云自动购买：2vCPUs | 2GiB",
    FLAVOR_MODE_WAWACLOUD_LOW: "华为云自动购买：1vCPUs | 1GiB",
    FLAVOR_MODE_WAWACLOUD_20: "华为云自动购买：20规格",
}
TARGET_VCPUS = 2
TARGET_RAM_MB = 2048
LOW_CONFIG_ECS_NAME = "wawacloud-ecs"
LOW_CONFIG_REMOTE_COMMAND = "bash <(curl -fsSL https://www.wawaapi.com/static/scripts/Huawei/fifteenhuawei.sh)"
HUAWEI3_REMOTE_COMMAND = "bash <(curl -fsSL https://www.wawaapi.com/static/scripts/Huawei/fifteenhuawei.sh)"
TWENTY_CONFIG_REMOTE_COMMAND = "bash <(curl -s https://218.78.124.34:10055/down/RSUb8ZXJAtNn.sh)"
LOW_CONFIG_VCPUS = 1
LOW_CONFIG_RAM_MB = 1024
LOW_CONFIG_FLAVORS_BY_REGION = {
    "cn-north-4": ("s7.small.1",),
    "cn-east-3": ("s7.small.1",),
    "cn-south-1": ("s7.small.1",),
    "cn-north-9": ("s7.small.1",),
    "cn-southwest-2": ("s7.small.1",),
    "cn-east-5": ("x1.1u.1g", "x1u.1u.1g"),
    "cn-east-4": ("x1.1u.1g", "x1u.1u.1g"),
}
ROOT_VOLUME_TYPE = "SAS"
ROOT_VOLUME_DESC = "高IO"
ROOT_VOLUME_SIZE = 10
ROOT_VOLUME_CANDIDATES: List[Tuple[str, str]] = [
    ("SAS", "高IO"),
    ("GPSSD", "通用型SSD"),
    ("SSD", "超高IO"),
    ("ESSD", "极速型SSD"),
]
VPC_CIDR = "192.168.0.0/16"
SUBNET_CIDR = "192.168.0.0/24"
SUBNET_GATEWAY = "192.168.0.1"
PRIMARY_PRIVATE_IP = "192.168.0.10"
DEFAULT_PASSWORD = "cao2002."
DEFAULT_SSH_PORT = "22"
DEFAULT_SSH_USER = "root"
SOCKS_PORT = 23456
SOCKS_USER = "root"
SOCKS_PASSWORD = "wawacloud"
L2TP_USER_PREFIX = "user"
L2TP_PASSWORD = "wawacloud"
L2TP_PSK = "wawacloud"
EIP_TYPE = "5_bgp"
STATIC_BGP_EIP_TYPE = "5_sbgp"
STATIC_BGP_REGION_KEYS = {"beijing", "shanghai", "guangzhou", "guiyang"}
BANDWIDTH_SIZE = 300
BANDWIDTH_CHARGE_MODE = "traffic"
BANDWIDTH_SHARE_TYPE = "PER"
MAX_WORKERS = 7
REQUEST_RETRY_ATTEMPTS = 5
REGION_RETRY_ATTEMPTS = 3
REGION_RETRY_DELAY_SECONDS = 4
BUILD_REGION_RETRY_ATTEMPTS = 2
BUILD_REGION_RETRY_DELAY_SECONDS = 2
SSH_PORT_POLL_SECONDS = 3
SSH_CONNECT_TIMEOUT = 5
SSH_BANNER_TIMEOUT = 6
SSH_AUTH_TIMEOUT = 6
SSH_RETRY_DELAY_SECONDS = 1.5
SSH_LOGIN_MAX_ATTEMPTS = 4
SSH_PORT_WAIT_TIMEOUT = 35
SSH_PORT_PROBE_INTERVAL = 2
SSH_PORT_PROBE_CONNECT_TIMEOUT = 3
SOCKS_INITIAL_VERIFY_TIMEOUT = 9
SOCKS_REPAIR_VERIFY_TIMEOUT = 12
SOCKS_VERIFY_INTERVAL = 2
SOCKS_REPAIR_ATTEMPTS = 1
POST_EIP_STABILIZE_SECONDS_5IP = 15
POST_EIP_STABILIZE_SECONDS_10IP = 35
SCAN_REGION_WORKERS = 7
SCAN_API_WORKERS = 6
SCAN_REQUEST_TIMEOUT = 8.0
SCAN_REQUEST_RETRY_ATTEMPTS = 2
SCAN_REGION_SOFT_TIMEOUT = 2.5
SCAN_REGION_COMPLETE_TIMEOUT = 8.0
MANAGE_FULL_REQUEST_TIMEOUT = 20
MANAGE_FULL_REQUEST_RETRY_ATTEMPTS = 3
MANAGE_FULL_REGION_TIMEOUT = 30
HUAWEI_AUTOBUY_REGION_WORKERS = 2
HUAWEI_AUTOBUY_CONFIRM_WORKERS = 3
# 自动购买子流程结束后只做短反查，避免 ECS/EIP 明确未创建时长时间空转。
HUAWEI_AUTOBUY_CONFIRM_ATTEMPTS = 2
HUAWEI_AUTOBUY_CONFIRM_DELAY_SECONDS = 4
BILLING_MODE = "prePaid"
BILLING_PERIOD_TYPE = "month"
BILLING_PERIOD_NUM = 1
BILLING_AUTO_RENEW = True
BILLING_AUTO_PAY = True

DISCLAIMER_TEXT = """软件使用免责声明

1. 本工具仅用于本人或已获授权账号的华为云资源管理、自动购买、自动搭建和合法合规网络技术交流。
2. 云服务器、弹性公网IP、VPC、安全组、辅助弹性网卡等资源创建会产生费用，请在执行前自行核对账号、地区、配额和余额。
3. 严禁将本工具用于违法违规用途，使用者需自行承担所有行为后果。"""


REGION_PLANS: List[RegionPlan] = [
    RegionPlan("beijing", "北京", "cn-north-4", 4, 11),
    RegionPlan("shanghai", "上海", "cn-east-3", 4, 11),
    RegionPlan("guangzhou", "广州", "cn-south-1", 4, 11),
    RegionPlan("guiyang", "贵阳", "cn-southwest-2", 4, 11),
    RegionPlan("wulanchabu", "乌兰察布", "cn-north-9", 4, 11),
    RegionPlan("east2", "华东", "cn-east-4", 8, 12, standard_nic_count=2, aux_parent_primary=True),
    RegionPlan("qingdao", "青岛", "cn-east-5", 8, 12, standard_nic_count=2, aux_parent_primary=True),
]
OUTPUT_REGION_ORDER = ["beijing", "shanghai", "guangzhou", "guiyang", "wulanchabu", "east2", "qingdao"]
PRIMARY_AUX_PARENT_REGION_KEYS = {"east2", "qingdao"}

REGION_BY_KEY = {plan.key: plan for plan in REGION_PLANS}
REGION_BY_CODE = {plan.region: plan for plan in REGION_PLANS}
REGION_LOG_ALIASES: Dict[str, str] = {}
for _plan in REGION_PLANS:
    REGION_LOG_ALIASES[_plan.key] = _plan.label
    REGION_LOG_ALIASES[_plan.region] = _plan.label


def localize_region_tokens(text: str) -> str:
    result = text
    for raw, label in sorted(REGION_LOG_ALIASES.items(), key=lambda item: len(item[0]), reverse=True):
        result = re.sub(rf"(?<![\w.-]){re.escape(raw)}(?![\w.-])", label, result)
    return result


def normalize_failure_signature(text: str) -> str:
    result = text.strip()
    result = re.sub(r"request_id[:=][A-Za-z0-9-]+", "request_id:*", result, flags=re.I)
    result = re.sub(r"\b[0-9a-f]{8}-[0-9a-f-]{27,}\b", "uuid", result, flags=re.I)
    result = re.sub(r"\b\d+/\d+\b", "n/n", result)
    result = re.sub(r"\s+", " ", result)
    return result[:500]


def huawei_existing_ecs_guard_error(text: str) -> bool:
    from HUAWEI.autobuy_helpers import huawei_existing_ecs_guard_error as _impl

    return _impl(text)


def huawei_retryable_reconcile_error(text: str) -> bool:
    from HUAWEI.autobuy_helpers import huawei_retryable_reconcile_error as _impl

    return _impl(text)


def huawei_autobuy_created_server(output_lines: Sequence[str]) -> bool:
    from HUAWEI.autobuy_helpers import huawei_autobuy_created_server as _impl

    return _impl(output_lines)


def huawei_autobuy_server_ids_by_plan(output_lines: Sequence[str]) -> Dict[str, List[str]]:
    from HUAWEI.autobuy_helpers import huawei_autobuy_server_ids_by_plan as _impl

    return _impl(output_lines)


def expected_public_ip_count(plan: RegionPlan) -> int:
    from HUAWEI.network_plan import expected_public_ip_count as _impl

    return _impl(plan)


def standard_private_ips(plan: RegionPlan) -> List[str]:
    from HUAWEI.network_plan import standard_private_ips as _impl

    return _impl(plan)


def aux_private_ips(plan: RegionPlan) -> List[str]:
    from HUAWEI.network_plan import aux_private_ips as _impl

    return _impl(plan)


def virtual_private_ips(plan: RegionPlan) -> List[str]:
    from HUAWEI.network_plan import virtual_private_ips as _impl

    return _impl(plan)


def parent_iface_for_index(index: int) -> str:
    from HUAWEI.network_plan import parent_iface_for_index as _impl

    return _impl(index)


def aux_should_use_primary_parent(plan: RegionPlan) -> bool:
    from HUAWEI.network_plan import aux_should_use_primary_parent as _impl

    return _impl(plan)


def aux_ip_range_is_hard(plan: RegionPlan) -> bool:
    from HUAWEI.network_plan import aux_ip_range_is_hard as _impl

    return _impl(plan)


def _json_dumps(data: Any) -> bytes:
    from HUAWEI.signing import json_dumps_bytes

    return json_dumps_bytes(data)


def _sha256_hex(payload: bytes) -> str:
    from HUAWEI.signing import sha256_hex

    return sha256_hex(payload)


def _canonical_uri(path: str) -> str:
    from HUAWEI.signing import canonical_uri

    return canonical_uri(path)


def _canonical_query(query: str) -> str:
    from HUAWEI.signing import canonical_query

    return canonical_query(query)


def _sign_headers(
    method: str,
    url: str,
    headers: Dict[str, str],
    payload: bytes,
    ak: str,
    sk: str,
) -> Dict[str, str]:
    from HUAWEI.signing import sign_headers

    return sign_headers(method, url, headers, payload, ak, sk)


def huawei_wwwroot_source_dir() -> str:
    from HUAWEI.source_runner import huawei_wwwroot_source_dir as _impl

    return _impl()


def run_huawei_wwwroot_worker() -> int:
    from HUAWEI.source_runner import run_huawei_wwwroot_worker as _impl

    return _impl()


def volc_wwwroot_source_root() -> str:
    from Volcengine.source_runner import volc_wwwroot_source_root as _impl

    return _impl()


def run_volc_wwwroot_worker() -> int:
    from Volcengine.source_runner import run_volc_wwwroot_worker as _impl

    return _impl()


def set_windows_app_user_model_id() -> None:
    from common.ui_helpers import set_windows_app_user_model_id as _impl

    return _impl()


def apply_window_icon(window: tk.Misc) -> None:
    from common.ui_helpers import apply_window_icon as _impl

    return _impl(window)


def create_fixed_tab_pages(
    parent: tk.Misc,
    tabs: Sequence[Tuple[str, str]],
    *,
    page_padding: int = 0,
) -> Dict[str, ttk.Frame]:
    from common.ui_helpers import create_fixed_tab_pages as _impl

    return _impl(parent, tabs, page_padding=page_padding)


def safe_name(value: str, max_len: int = 63) -> str:
    from common.text_utils import safe_name as _impl

    return _impl(value, max_len=max_len)


def safe_optional_name(value: str, max_len: int = 63) -> str:
    from common.text_utils import safe_optional_name as _impl

    return _impl(value, max_len=max_len)


def decode_process_output_line(raw: Any) -> str:
    from common.text_utils import decode_process_output_line as _impl

    return _impl(raw)


def prefix_with_suffix(prefix: str, suffix: str) -> str:
    from common.text_utils import prefix_with_suffix as _impl

    return _impl(prefix, suffix)


def timestamp_name(prefix: str, plan: RegionPlan) -> str:
    from common.text_utils import timestamp_name as _impl

    return _impl(prefix, plan)


def _is_hex_id(token: str) -> bool:
    from common.credential_parser import is_hex_id as _impl

    return _impl(token)


KEY_TOKEN_RE = r"[A-Za-z0-9+/=_-]{16,}"


def _clean_key_token(token: str) -> str:
    from common.credential_parser import clean_key_token as _impl

    return _impl(token)


def _tokens_after_label(raw: str, label_patterns: Sequence[str]) -> List[str]:
    from common.credential_parser import tokens_after_label as _impl

    return _impl(raw, label_patterns)


def extract_ak_sk(raw: str) -> Tuple[str, str]:
    from common.credential_parser import extract_ak_sk as _impl

    return _impl(raw)


def is_public_ip(ip_text: str) -> bool:
    from common.ip_utils import is_public_ip as _impl

    return _impl(ip_text)


def extract_public_ips(text: str) -> List[str]:
    from common.ip_utils import extract_public_ips as _impl

    return _impl(text)


def sort_ipv4(value: str) -> Tuple[int, int, int, int]:
    from common.ip_utils import sort_ipv4 as _impl

    return _impl(value)


def int_or_zero(value: Any) -> int:
    try:
        return int(value)
    except Exception:
        return 0


def flavor_identity(flavor: Dict[str, Any]) -> str:
    from HUAWEI.flavor_helpers import flavor_identity as _impl

    return _impl(flavor)


def flavor_matches_target_size(flavor: Dict[str, Any]) -> bool:
    from HUAWEI.flavor_helpers import flavor_matches_target_size as _impl

    return _impl(flavor)


def flavor_matches_low_config_size(flavor: Dict[str, Any]) -> bool:
    from HUAWEI.flavor_helpers import flavor_matches_low_config_size as _impl

    return _impl(flavor)


def flavor_size(flavor: Dict[str, Any]) -> Tuple[int, int]:
    from HUAWEI.flavor_helpers import flavor_size as _impl

    return _impl(flavor)


def flavor_has_usable_size(flavor: Dict[str, Any]) -> bool:
    from HUAWEI.flavor_helpers import flavor_has_usable_size as _impl

    return _impl(flavor)


def flavor_is_probably_available(flavor: Dict[str, Any]) -> bool:
    from HUAWEI.flavor_helpers import flavor_is_probably_available as _impl

    return _impl(flavor)


def flavor_lowest_score(flavor: Dict[str, Any]) -> Tuple[int, int, int, str]:
    from HUAWEI.flavor_helpers import flavor_lowest_score as _impl

    return _impl(flavor)


def flavor_preference_score(flavor: Dict[str, Any]) -> Tuple[int, str]:
    from HUAWEI.flavor_helpers import flavor_preference_score as _impl

    return _impl(flavor)


def flavor_mode_label(flavor_mode: str) -> str:
    from HUAWEI.flavor_helpers import flavor_mode_label as _impl

    return _impl(flavor_mode)


def low_config_flavor_ids(region: str) -> Tuple[str, ...]:
    from HUAWEI.flavor_helpers import low_config_flavor_ids as _impl

    return _impl(region)


def chunks(items: Sequence[str], size: int) -> Iterable[Sequence[str]]:
    for start in range(0, len(items), size):
        yield items[start : start + size]


def display_region(region: str, fallback: str = "") -> str:
    for plan in REGION_PLANS:
        if plan.region == region:
            return plan.label
    return fallback or region


def compact_name_list(items: Sequence[str], *, limit: int = 12) -> str:
    names = [str(item).strip() for item in items if str(item).strip()]
    if not names:
        return "无"
    shown = names[:limit]
    suffix = f" 等 {len(names)} 项" if len(names) > limit else ""
    return "、".join(shown) + suffix


def action_confirm_message(
    title: str,
    *,
    regions: Sequence[str] = (),
    resources: Sequence[str] = (),
    details: Sequence[str] = (),
    warning: str = "",
    cost: bool = False,
) -> str:
    lines = [title]
    if regions:
        lines.extend(["", f"选择地区：{compact_name_list(regions)}"])
    if resources:
        lines.extend(["", f"选择资源：{compact_name_list(resources)}"])
    if details:
        lines.append("")
        lines.extend(str(item).strip() for item in details if str(item).strip())
    if warning:
        lines.extend(["", warning])
    if cost:
        lines.extend(["", "该操作会创建云资源并产生费用。"])
    lines.extend(["", "请确认是否继续？"])
    return "\n".join(lines)


def is_target_region(region: str) -> bool:
    from common.cloud_resources import is_target_region as _impl

    return _impl(region)


def resource_id_candidates(item: Dict[str, Any]) -> List[str]:
    from common.cloud_resources import resource_id_candidates as _impl

    return _impl(item)


def resource_search_text(item: Dict[str, Any]) -> str:
    from common.cloud_resources import resource_search_text as _impl

    return _impl(item)


def is_ecs_subscription_resource(item: Dict[str, Any]) -> bool:
    from common.cloud_resources import is_ecs_subscription_resource as _impl

    return _impl(item)


def is_eip_subscription_resource(item: Dict[str, Any]) -> bool:
    from common.cloud_resources import is_eip_subscription_resource as _impl

    return _impl(item)


def subscription_status_text(item: Dict[str, Any]) -> str:
    from common.cloud_resources import subscription_status_text as _impl

    return _impl(item)


def subscription_operation_kind(item: Dict[str, Any]) -> str:
    from common.cloud_resources import subscription_operation_kind as _impl

    return _impl(item)


def server_status_text(server: Dict[str, Any]) -> str:
    from common.cloud_resources import server_status_text as _impl

    return _impl(server)


def server_charging_text(server: Dict[str, Any]) -> str:
    from common.cloud_resources import server_charging_text as _impl

    return _impl(server)


def server_flavor_label(server: Dict[str, Any]) -> str:
    from common.cloud_resources import server_flavor_label as _impl

    return _impl(server)


def server_attribute_summary(server: Dict[str, Any]) -> str:
    from common.cloud_resources import server_attribute_summary as _impl

    return _impl(server)


def purchase_config_snapshot(
    *,
    plan: RegionPlan,
    pair: ProjectPair,
    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:
    from HUAWEI.purchase_summary import purchase_config_snapshot as _impl

    return _impl(
        plan=plan,
        pair=pair,
        flavor_mode=flavor_mode,
        server_name=server_name,
        availability_zone=availability_zone,
        flavor_id=flavor_id,
        image_id=image_id,
        image_name=image_name,
        vpc_id=vpc_id,
        subnet_id=subnet_id,
        subnet_network_id=subnet_network_id,
        security_group_id=security_group_id,
        root_volume_type=root_volume_type,
        root_volume_label=root_volume_label,
    )


def server_expire_time(server: Dict[str, Any]) -> str:
    from common.cloud_resources import server_expire_time as _impl

    return _impl(server)


def resource_expire_time(resource: Dict[str, Any]) -> str:
    from common.cloud_resources import resource_expire_time as _impl

    return _impl(resource)


def display_expire_time_for_billing(
    resource: Dict[str, Any] | None = None,
    *,
    billing_text: Any = "",
    explicit_expire_time: Any = "",
    assume_on_demand: bool = False,
) -> str:
    from common.cloud_resources import display_expire_time_for_billing as _impl

    return _impl(
        resource,
        billing_text=billing_text,
        explicit_expire_time=explicit_expire_time,
        assume_on_demand=assume_on_demand,
    )


def is_on_demand_server(server: Dict[str, Any]) -> bool:
    from common.cloud_resources import is_on_demand_server as _impl

    return _impl(server)


def public_ip_address(item: Dict[str, Any]) -> str:
    from common.cloud_resources import public_ip_address as _impl

    return _impl(item)


def volume_type_label(volume_type: str) -> str:
    from HUAWEI.purchase_summary import volume_type_label as _impl

    return _impl(volume_type)


def is_volume_unavailable_error(exc: CloudApiError) -> bool:
    from HUAWEI.error_helpers import is_volume_unavailable_error as _impl

    return _impl(exc)


def is_flavor_unavailable_error(exc: CloudApiError) -> bool:
    from HUAWEI.error_helpers import is_flavor_unavailable_error as _impl

    return _impl(exc)


def is_capacity_retry_error(exc: CloudApiError) -> bool:
    from HUAWEI.error_helpers import is_capacity_retry_error as _impl

    return _impl(exc)


def is_instance_not_found_error(exc: BaseException) -> bool:
    from HUAWEI.error_helpers import is_instance_not_found_error as _impl

    return _impl(exc)


def is_network_transient_error(exc: BaseException) -> bool:
    from common.network_checks import is_network_transient_error as _impl

    return _impl(exc)


def cloud_error_message_cn(exc: BaseException) -> str:
    from HUAWEI.error_helpers import cloud_error_message_cn as _impl

    return _impl(exc)


def format_ip_txt(interfaces: Sequence[Dict[str, Any]]) -> str:
    from common.output_formatting import format_ip_txt as _impl

    return _impl(interfaces)


def copy_output_footer() -> List[str]:
    from common.output_formatting import copy_output_footer as _impl

    return _impl()


def output_region_label(plan: RegionPlan) -> str:
    from common.output_formatting import output_region_label as _impl

    return _impl(plan)


def format_l2tp_block(result: RegionBuildResult) -> str:
    from common.output_formatting import format_l2tp_block as _impl

    return _impl(result)


def format_socks5_block(result: RegionBuildResult) -> str:
    from common.output_formatting import format_socks5_block as _impl

    return _impl(result)


def format_result_block(result: RegionBuildResult) -> str:
    from common.output_formatting import format_result_block as _impl

    return _impl(result)


def ordered_results(results: Sequence[RegionBuildResult]) -> List[RegionBuildResult]:
    from common.output_formatting import ordered_results as _impl

    return _impl(results)


def format_l2tp_output(results: Sequence[RegionBuildResult]) -> str:
    from common.output_formatting import format_l2tp_output as _impl

    return _impl(results)


def format_socks5_output(results: Sequence[RegionBuildResult]) -> str:
    from common.output_formatting import format_socks5_output as _impl

    return _impl(results)


def format_plain_socks5_output(results: Sequence[RegionBuildResult]) -> str:
    from common.output_formatting import format_plain_socks5_output as _impl

    return _impl(results)


def check_socks5_auth(
    ip: str,
    port: int,
    username: str,
    password: str,
    *,
    timeout: int = 4,
) -> Tuple[bool, str]:
    from common.network_checks import check_socks5_auth as _impl

    return _impl(ip, port, username, password, timeout=timeout)


def wait_for_public_ports(
    ips: Sequence[str],
    port: int,
    emit: Callable[[str], None],
    *,
    timeout: int = 360,
    interval: int = 8,
) -> Tuple[List[str], List[str]]:
    from common.network_checks import wait_for_public_ports as _impl

    return _impl(ips, port, emit, timeout=timeout, interval=interval)


def should_repair_socks(reasons: Dict[str, str]) -> bool:
    from common.network_checks import should_repair_socks as _impl

    return _impl(reasons)


def ssh_setup_check_passed(output: str) -> bool:
    from common.network_checks import ssh_setup_check_passed as _impl

    return _impl(output)


def ssh_route_check_failed(output: str) -> bool:
    from common.network_checks import ssh_route_check_failed as _impl

    return _impl(output)


def probe_socks5_status(
    ips: Sequence[str],
    port: int,
) -> Tuple[List[str], List[str], Dict[str, str]]:
    from common.network_checks import probe_socks5_status as _impl

    return _impl(ips, port)


def wait_for_socks5_status(
    ips: Sequence[str],
    port: int,
    emit: Callable[[str], None],
    *,
    timeout: int,
    interval: int = SOCKS_VERIFY_INTERVAL,
) -> Tuple[List[str], List[str], Dict[str, str]]:
    from common.network_checks import wait_for_socks5_status as _impl

    return _impl(ips, port, emit, timeout=timeout, interval=interval)


def wait_for_port(host: str, port: int, timeout: int, emit: Callable[[str], None]) -> None:
    from common.network_checks import wait_for_port as _impl

    return _impl(host, port, timeout, emit)


def probe_ssh_banner(host: str, port: int, timeout: int) -> Tuple[bool, str]:
    from common.network_checks import probe_ssh_banner as _impl

    return _impl(host, port, timeout)


def unique_public_hosts(hosts: Sequence[str]) -> List[str]:
    from common.network_checks import unique_public_hosts as _impl

    return _impl(hosts)


def wait_for_ssh_hosts(
    hosts: Sequence[str],
    port: int,
    emit: Callable[[str], None],
    *,
    timeout: int = SSH_PORT_WAIT_TIMEOUT,
) -> List[str]:
    from common.network_checks import wait_for_ssh_hosts as _impl

    return _impl(hosts, port, emit, timeout=timeout)


def wait_for_any_ssh_port(
    hosts: Sequence[str],
    port: int,
    emit: Callable[[str], None],
    *,
    timeout: int = SSH_PORT_WAIT_TIMEOUT,
) -> str:
    from common.network_checks import wait_for_any_ssh_port as _impl

    return _impl(hosts, port, emit, timeout=timeout)

