package com.dragonssh.xhttpdemo;

final class ConfigUtils {
    private ConfigUtils() { }

    static String normalizePath(String path) {
        if (path == null || path.trim().isEmpty()) return "";
        String normalized = path.trim();
        if (!normalized.startsWith("/")) normalized = "/" + normalized;
        while (normalized.length() > 1 && normalized.endsWith("/")) {
            normalized = normalized.substring(0, normalized.length() - 1);
        }
        return normalized;
    }

    static boolean isValidPort(String value) {
        try {
            int port = Integer.parseInt(value);
            return port >= 1 && port <= 65535;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    static boolean isHostPort(String value) {
        if (value == null || value.trim().isEmpty()) return false;
        String clean = value.trim();
        int separator = clean.lastIndexOf(':');
        if (separator <= 0 || separator == clean.length() - 1) return false;
        return isValidPort(clean.substring(separator + 1));
    }

    static String displayValue(String value) {
        return value == null || value.trim().isEmpty() ? "—" : value.trim();
    }

    static String formatHostPort(String host, String port) {
        String cleanHost = displayValue(host);
        if (cleanHost.contains(":") && !cleanHost.startsWith("[") && !"—".equals(cleanHost)) {
            cleanHost = "[" + cleanHost + "]";
        }
        return cleanHost + ":" + displayValue(port);
    }
}
