#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import site
import ttp_logger
import time
import socket
import ipaddress


def input_ip_transform(input_ip: str, max_retries: int = 3) -> str:
    if not input_ip or is_valid_ip(input_ip):
        return input_ip

    for attempt in range(max_retries):
        try:
            ip = socket.gethostbyname(input_ip)
            ttp_logger.LOGGER.info(f"transform {input_ip} to {ip}")
            return ip
        except socket.error as e:
            ttp_logger.LOGGER.warning(f"Attempt {attempt + 1} failed to resolve {input_ip}, {str(e)}")
            if attempt == max_retries - 1:
                ttp_logger.LOGGER.error(f"Failed to resolve {input_ip} after {max_retries} attempts")
                return input_ip
        time.sleep(1)

    return input_ip


def is_valid_ip(ip_str):
    return is_valid_ipv4(ip_str) or is_valid_ipv6(ip_str)


def is_valid_ipv4(ip: str) -> bool:
    try:
        socket.inet_pton(socket.AF_INET, ip)
        return True
    except socket.error:
        ttp_logger.LOGGER.warning("input illegal ipv4 address: %s", ip)
        return False


def is_valid_ipv6(ip: str) -> bool:
    try:
        socket.inet_pton(socket.AF_INET6, ip)
        return True
    except socket.error:
        ttp_logger.LOGGER.warning("input illegal ipv6 address: %s", ip)
        return False


def is_zero_ip(ip_str):
    try:
        ip = ipaddress.ip_address(ip_str.strip())
        return ip == ipaddress.IPv4Address('0.0.0.0') or \
            ip == ipaddress.IPv6Address('::')
    except ValueError:
        return False


def get_env_var_int_safely(env_var_name, default_value, min_value=None, max_value=None):
    try:
        temp_var = os.getenv(env_var_name, str(default_value))
        if len(temp_var) > 1000:
            temp_var = default_value
        temp_var = int(temp_var)
        if min_value is not None and temp_var < min_value:
            ttp_logger.LOGGER.warning(f"Environment variable {env_var_name} is below the minimum value, "
                                      f"using default value: {default_value}")
            return default_value
        if max_value is not None and temp_var > max_value:
            ttp_logger.LOGGER.warning(f"Environment variable {env_var_name} is above the maximum value, "
                                      f"using default value: {default_value}")
            return default_value
        result = temp_var
        return result
    except Exception as e:
        ttp_logger.LOGGER.warning(f"invalid env variable:{env_var_name}, use default value {default_value}: {e}")
        return default_value