package com.xfestudio.xfeservermanager.infra.config;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.URI;
import java.nio.file.Path;
import java.time.Duration;
import java.time.DateTimeException;
import java.time.ZoneId;
import java.util.List;
import java.util.Objects;

/**
 * Startup-level server configuration. Dynamic policy and RBAC state belongs in
 * the control database, not in this object.
 */
public record ServerConfiguration(
        InetAddress bindAddress,
        int port,
        String publicBaseUrl,
        List<String> trustedProxyCidrs,
        Path dataDirectory,
        Duration idleSessionTimeout,
        Duration absoluteSessionTimeout,
        Duration recentAuthenticationWindow,
        int httpThreads,
        int maximumSseClients,
        boolean webConsoleEnabled,
        boolean rawItemEditingEnabled,
        boolean metricsEnabled,
        boolean moderationEnabled,
        boolean claimsEnabled,
        boolean worldTrackingEnabled,
        boolean rollbackEnabled,
        boolean joinExperienceEnabled,
        String defaultMessageSender,
        boolean joinWelcomeEnabled,
        String joinWelcomeMessage,
        boolean firstJoinMessageEnabled,
        String firstJoinMessage,
        boolean dailyAnnouncementsEnabled,
        List<String> dailyAnnouncements,
        String announcementTimeZone,
        boolean rulesReminderEnabled,
        String rulesMessage,
        boolean maintenanceJoinReminderEnabled,
        CrashProtectionConfiguration crashProtection) {

    public ServerConfiguration {
        Objects.requireNonNull(bindAddress, "bindAddress");
        Objects.requireNonNull(publicBaseUrl, "publicBaseUrl");
        trustedProxyCidrs = List.copyOf(trustedProxyCidrs);
        Objects.requireNonNull(dataDirectory, "dataDirectory");
        Objects.requireNonNull(idleSessionTimeout, "idleSessionTimeout");
        Objects.requireNonNull(absoluteSessionTimeout, "absoluteSessionTimeout");
        Objects.requireNonNull(recentAuthenticationWindow, "recentAuthenticationWindow");
        Objects.requireNonNull(defaultMessageSender, "defaultMessageSender");
        rejectDefaultMessageSenderControls(defaultMessageSender);
        defaultMessageSender = defaultMessageSender.strip();
        Objects.requireNonNull(joinWelcomeMessage, "joinWelcomeMessage");
        Objects.requireNonNull(firstJoinMessage, "firstJoinMessage");
        dailyAnnouncements = List.copyOf(dailyAnnouncements);
        Objects.requireNonNull(announcementTimeZone, "announcementTimeZone");
        Objects.requireNonNull(rulesMessage, "rulesMessage");
        Objects.requireNonNull(crashProtection, "crashProtection");
        if (port < 1 || port > 65_535) {
            throw new IllegalArgumentException("port must be between 1 and 65535");
        }
        if (httpThreads < 2 || httpThreads > 64) {
            throw new IllegalArgumentException("httpThreads must be between 2 and 64");
        }
        if (maximumSseClients < 1 || maximumSseClients > 1_000) {
            throw new IllegalArgumentException("maximumSseClients must be between 1 and 1000");
        }
        URI publicUri = URI.create(publicBaseUrl);
        if (publicUri.getHost() == null
                || !("http".equalsIgnoreCase(publicUri.getScheme())
                        || "https".equalsIgnoreCase(publicUri.getScheme()))
                || publicUri.getUserInfo() != null
                || publicUri.getRawQuery() != null
                || publicUri.getRawFragment() != null
                || (publicUri.getPath() != null && !publicUri.getPath().isEmpty()
                        && !"/".equals(publicUri.getPath()))) {
            throw new IllegalArgumentException("publicBaseUrl must be an HTTP(S) origin");
        }
        if (idleSessionTimeout.isNegative() || idleSessionTimeout.isZero()
                || absoluteSessionTimeout.compareTo(idleSessionTimeout) < 0) {
            throw new IllegalArgumentException("invalid session timeout configuration");
        }
        if (recentAuthenticationWindow.isNegative() || recentAuthenticationWindow.isZero()
                || recentAuthenticationWindow.compareTo(absoluteSessionTimeout) > 0) {
            throw new IllegalArgumentException("invalid recent authentication window");
        }
        if (!bindAddress.isLoopbackAddress()
                && !"https".equalsIgnoreCase(publicUri.getScheme())) {
            throw new IllegalArgumentException(
                    "a non-loopback HTTP listener requires an HTTPS publicBaseUrl");
        }
        validateDefaultMessageSender(defaultMessageSender);
        validateMessage("joinWelcomeMessage", joinWelcomeMessage);
        validateMessage("firstJoinMessage", firstJoinMessage);
        validateMessage("rulesMessage", rulesMessage);
        if (dailyAnnouncements.size() > 20) {
            throw new IllegalArgumentException("dailyAnnouncements cannot contain more than 20 messages");
        }
        dailyAnnouncements.forEach(message -> validateMessage("dailyAnnouncements", message));
        try {
            ZoneId.of(announcementTimeZone);
        } catch (DateTimeException exception) {
            throw new IllegalArgumentException("announcementTimeZone must be a valid zone id", exception);
        }
    }

    public static ServerConfiguration secureDefaults(Path dataDirectory) {
        try {
            return new ServerConfiguration(
                    InetAddress.getByName("127.0.0.1"),
                    8_765,
                    "http://127.0.0.1:8765",
                    List.of(),
                    dataDirectory,
                    Duration.ofMinutes(30),
                    Duration.ofHours(8),
                    Duration.ofMinutes(5),
                    8,
                    20,
                    false,
                    false,
                    false,
                    false,
                    false,
                    false,
                    false,
                    false,
                    DEFAULT_MESSAGE_SENDER,
                    true,
                    "Welcome back, {player}! / 欢迎回来，{player}！",
                    true,
                    "Welcome to the server for the first time, {player}! / 欢迎首次来到服务器，{player}！",
                    true,
                    List.of("Have a great day, {player}! Online: {online}/{maxPlayers} / 祝你今天游戏愉快！在线：{online}/{maxPlayers}"),
                    ZoneId.systemDefault().getId(),
                    true,
                    "Please follow the server rules. Use /xfesm for help. / 请遵守服务器规则，需要帮助可使用 /xfesm。",
                    true,
                    CrashProtectionConfiguration.defaults());
        } catch (UnknownHostException impossible) {
            throw new IllegalStateException("loopback address is unavailable", impossible);
        }
    }

    public boolean isLoopbackOnly() {
        return bindAddress.isLoopbackAddress();
    }

    /** Product default retained for old configuration files and callers without an override. */
    public static final String DEFAULT_MESSAGE_SENDER = "XFEServerManager";

    private static void validateDefaultMessageSender(String value) {
        if (value.isEmpty() || value.length() > 64) {
            throw new IllegalArgumentException(
                    "defaultMessageSender must contain 1 to 64 non-control characters on one line");
        }
    }

    private static void rejectDefaultMessageSenderControls(String value) {
        if (value.codePoints().anyMatch(Character::isISOControl)) {
            throw new IllegalArgumentException(
                    "defaultMessageSender must contain 1 to 64 non-control characters on one line");
        }
    }

    private static void validateMessage(String name, String value) {
        RichTextMessageValidator.validate(name, value);
    }
}
