package com.xfestudio.xfeservermanager.infra.http;

import com.google.gson.JsonParseException;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import com.xfestudio.xfeservermanager.api.audit.AuditEvent;
import com.xfestudio.xfeservermanager.api.audit.AuditOutcome;
import com.xfestudio.xfeservermanager.api.command.CommandSourceKind;
import com.xfestudio.xfeservermanager.core.player.PlayerOperationException;
import com.xfestudio.xfeservermanager.core.operation.InvalidOperationTransitionException;
import com.xfestudio.xfeservermanager.core.operation.OperationNotFoundException;
import com.xfestudio.xfeservermanager.core.policy.InvalidPolicyException;
import com.xfestudio.xfeservermanager.core.policy.NoPolicyDraftException;
import com.xfestudio.xfeservermanager.core.policy.PolicyDraftConflictException;
import com.xfestudio.xfeservermanager.core.policy.PolicyDraftPresentException;
import com.xfestudio.xfeservermanager.core.policy.PolicyVersionConflictException;
import com.xfestudio.xfeservermanager.core.trigger.TriggerRevisionConflictException;
import com.xfestudio.xfeservermanager.core.trigger.TriggerStateRevisionConflictException;
import com.xfestudio.xfeservermanager.core.economy.EconomyConflictException;
import com.xfestudio.xfeservermanager.infra.config.ServerConfiguration;
import com.xfestudio.xfeservermanager.infra.security.AuthenticatedPrincipal;
import com.xfestudio.xfeservermanager.infra.security.AccountConflictException;
import com.xfestudio.xfeservermanager.infra.security.AuthenticationService;
import com.xfestudio.xfeservermanager.infra.security.AuthenticationService.AuthenticationException;
import com.xfestudio.xfeservermanager.infra.security.BootstrapTokenService;
import com.xfestudio.xfeservermanager.infra.security.Capability;
import com.xfestudio.xfeservermanager.infra.security.Role;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Clock;
import java.time.Instant;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;

/** Embedded, loopback-first REST and SSE server. */
public final class HttpApiServer implements AutoCloseable {
    private static final int MAXIMUM_JSON_BYTES = 2 * 1024 * 1024;
    /** Allows a 64 KiB UTF-16 DSL even when non-ASCII/control characters expand in JSON/UTF-8. */
    private static final int MAXIMUM_TRIGGER_VALIDATION_JSON_BYTES = 400 * 1024;
    private static final Duration GATEWAY_TIMEOUT = Duration.ofSeconds(3);
    private static final long SSE_SESSION_RECHECK_NANOS = TimeUnit.SECONDS.toNanos(5);
    private static final String SESSION_COOKIE = "xfesm_session";
    private static final UUID ANONYMOUS_IDEMPOTENCY_SCOPE = new UUID(0L, 0L);

    private final ServerConfiguration configuration;
    private final AuthenticationService authentication;
    private final BootstrapTokenService bootstrapTokens;
    private final ManagementGateway gateway;
    private final JsonCodec json;
    private final SseBroker events;
    private final TrustedProxyResolver proxyResolver;
    private final String metricsToken;
    private final OpenMetricsFormatter metricsFormatter = new OpenMetricsFormatter();
    private final IdempotencyRegistry idempotency =
            new IdempotencyRegistry(4_096, Duration.ofMinutes(15), Clock.systemUTC());
    private final AtomicReference<State> state = new AtomicReference<>(State.STOPPED);
    private final AtomicReference<Map<String, Object>> pendingSettings =
            new AtomicReference<>(Map.of());
    private HttpServer server;
    private ExecutorService executor;

    public HttpApiServer(
            ServerConfiguration configuration,
            AuthenticationService authentication,
            BootstrapTokenService bootstrapTokens,
            ManagementGateway gateway,
            JsonCodec json,
            SseBroker events,
            String metricsToken) {
        this.configuration = configuration;
        this.authentication = authentication;
        this.bootstrapTokens = bootstrapTokens;
        this.gateway = gateway;
        this.json = json;
        this.events = events;
        this.proxyResolver = new TrustedProxyResolver(configuration.trustedProxyCidrs());
        this.metricsToken = metricsToken == null ? "" : metricsToken;
    }

    public synchronized void start() throws IOException {
        if (!state.compareAndSet(State.STOPPED, State.STARTING)) {
            throw new IllegalStateException("HTTP server is already active");
        }
        try {
            server = HttpServer.create(
                    new InetSocketAddress(configuration.bindAddress(), configuration.port()), 64);
            executor = new ThreadPoolExecutor(
                    configuration.httpThreads() + configuration.maximumSseClients(),
                    configuration.httpThreads() + configuration.maximumSseClients(),
                    0L,
                    TimeUnit.MILLISECONDS,
                    new ArrayBlockingQueue<>(256),
                    runnable -> {
                        Thread thread = new Thread(runnable, "xfesm-http");
                        thread.setDaemon(true);
                        return thread;
                    },
                    new ThreadPoolExecutor.AbortPolicy());
            server.setExecutor(executor);
            server.createContext("/", this::handle);
            server.start();
            state.set(State.RUNNING);
        } catch (IOException | RuntimeException exception) {
            state.set(State.FAILED);
            close();
            throw exception;
        }
    }

    public State state() {
        return state.get();
    }

    public URI baseUri() {
        String host = configuration.bindAddress().getHostAddress().replace("%", "%25");
        return URI.create("http://" + (host.contains(":") ? '[' + host + ']' : host) + ":"
                + configuration.port());
    }

    private void handle(HttpExchange exchange) throws IOException {
        String requestId = requestId(exchange);
        applySecurityHeaders(exchange.getResponseHeaders(), requestId);
        try {
            route(exchange, requestId);
        } catch (AuthenticationException exception) {
            int status = "rate_limited".equals(exception.code()) ? 429 : 401;
            if (status == 429) exchange.getResponseHeaders().set("Retry-After", "600");
            problem(exchange, status, "Authentication failed", exception.getMessage(), requestId);
        } catch (ReauthenticationRequiredException exception) {
            problem(exchange, 428, "Reauthentication required", exception.getMessage(), requestId);
        } catch (ForbiddenException exception) {
            problem(exchange, 403, "Forbidden", exception.getMessage(), requestId);
        } catch (SecurityException exception) {
            problem(exchange, 403, "Forbidden", exception.getMessage(), requestId);
        } catch (AccountConflictException exception) {
            problem(exchange, 409, "Account conflict", exception.getMessage(), requestId);
        } catch (IdempotencyRegistry.IdempotencyConflictException exception) {
            problem(exchange, 409, "Idempotency conflict", exception.getMessage(), requestId);
        } catch (IdempotencyRegistry.IdempotencyCapacityException exception) {
            problem(exchange, 503, "Server busy", exception.getMessage(), requestId);
        } catch (NotFoundException | java.util.NoSuchElementException exception) {
            problem(exchange, 404, "Not found", exception.getMessage(), requestId);
        } catch (ServiceUnavailableException exception) {
            problem(exchange, 503, "Service unavailable", exception.getMessage(), requestId);
        } catch (UnsupportedOperationException exception) {
            problem(exchange, 501, "Not implemented", exception.getMessage(), requestId);
        } catch (JsonCodec.PayloadTooLargeException exception) {
            problem(exchange, 413, "Payload too large", exception.getMessage(), requestId);
        } catch (JsonParseException | IllegalArgumentException exception) {
            int status = domainFailureStatus(exception);
            if (status == 0) status = 400;
            problem(exchange, status, domainFailureTitle(status), safeMessage(exception), requestId);
        } catch (CompletionException exception) {
            handleCompletionFailure(exchange, exception, requestId);
        } catch (InterruptedException interrupted) {
            Thread.currentThread().interrupt();
        } catch (IOException transportFailure) {
            throw transportFailure;
        } catch (Exception exception) {
            int domainStatus = domainFailureStatus(exception);
            if (domainStatus == 0) {
                problem(exchange, 500, "Internal server error", safeMessage(exception), requestId);
            } else {
                problem(
                        exchange,
                        domainStatus,
                        domainFailureTitle(domainStatus),
                        safeMessage(exception),
                        requestId);
            }
        } finally {
            exchange.close();
        }
    }

    private void handleCompletionFailure(
            HttpExchange exchange, CompletionException failure, String requestId) throws IOException {
        Throwable cause = failure;
        while ((cause instanceof CompletionException
                        || cause instanceof java.util.concurrent.ExecutionException)
                && cause.getCause() != null) {
            cause = cause.getCause();
        }
        if (cause instanceof TimeoutException) {
            exchange.getResponseHeaders().set("Retry-After", "1");
            problem(exchange, 504, "Request still pending",
                    "the operation outcome is not known yet; retry with the same Idempotency-Key", requestId);
        } else if (cause instanceof AuthenticationException authenticationFailure) {
            int status = "rate_limited".equals(authenticationFailure.code()) ? 429 : 401;
            if (status == 429) exchange.getResponseHeaders().set("Retry-After", "600");
            problem(exchange, status, "Authentication failed", authenticationFailure.getMessage(), requestId);
        } else if (cause instanceof ReauthenticationRequiredException) {
            problem(exchange, 428, "Reauthentication required", safeMessage(cause), requestId);
        } else if (cause instanceof ForbiddenException || cause instanceof SecurityException) {
            problem(exchange, 403, "Forbidden", safeMessage(cause), requestId);
        } else if (cause instanceof IdempotencyRegistry.IdempotencyConflictException) {
            problem(exchange, 409, "Idempotency conflict", safeMessage(cause), requestId);
        } else if (cause instanceof AccountConflictException) {
            problem(exchange, 409, "Account conflict", safeMessage(cause), requestId);
        } else if (cause instanceof IdempotencyRegistry.IdempotencyCapacityException
                || cause instanceof ServiceUnavailableException) {
            problem(exchange, 503, "Service unavailable", safeMessage(cause), requestId);
        } else if (cause instanceof NotFoundException
                || cause instanceof java.util.NoSuchElementException) {
            problem(exchange, 404, "Not found", safeMessage(cause), requestId);
        } else if (cause instanceof UnsupportedOperationException) {
            problem(exchange, 501, "Not implemented", safeMessage(cause), requestId);
        } else if (domainFailureStatus(cause) != 0) {
            int status = domainFailureStatus(cause);
            problem(exchange, status, domainFailureTitle(status), safeMessage(cause), requestId);
        } else if (cause instanceof JsonParseException || cause instanceof IllegalArgumentException) {
            problem(exchange, 400, "Invalid request", safeMessage(cause), requestId);
        } else {
            problem(exchange, 500, "Operation failed", safeMessage(cause), requestId);
        }
    }

    private void route(HttpExchange exchange, String requestId) throws Exception {
        String method = exchange.getRequestMethod().toUpperCase(Locale.ROOT);
        String path = normalizedPath(exchange.getRequestURI());

        if (method.equals("GET")
                && (path.equals("/healthz") || path.equals("/api/v1/healthz"))) {
            boolean serverReady = gateway.serverReady();
            respondJson(exchange, serverReady ? 200 : 503, Map.of(
                    "http", state.get().name().toLowerCase(Locale.ROOT),
                    "serverReady", serverReady,
                    "sseClients", events.subscriberCount()));
            return;
        }
        if (method.equals("GET")
                && (path.equals("/metrics") || path.equals("/api/v1/metrics"))) {
            handleMetrics(exchange);
            return;
        }
        if (method.equals("GET") && path.equals("/api/v1/meta")) {
            respondJson(exchange, 200, Map.of(
                    "name", "XFEServerManager",
                    "apiVersion", "v1",
                    "setupRequired", ownerSetupRequired(),
                    "serverReady", gateway.serverReady()));
            return;
        }
        if (method.equals("POST")
                && (path.equals("/api/v1/setup")
                        || path.equals("/api/v1/auth/bootstrap"))) {
            requirePublicOrigin(exchange);
            handleSetup(exchange);
            return;
        }
        if (method.equals("POST") && path.equals("/api/v1/auth/login")) {
            requirePublicOrigin(exchange);
            handleLogin(exchange);
            return;
        }
        if (method.equals("GET")
                && (path.equals("/api/v1/session") || path.equals("/api/v1/auth/session"))) {
            handleSession(exchange);
            return;
        }
        if (method.equals("GET") && !path.startsWith("/api/")) {
            serveStatic(exchange, path);
            return;
        }

        AuthContext auth = requireAuthentication(exchange);
        if (method.equals("POST") && path.equals("/api/v1/auth/logout")) {
            requireMutationSecurity(exchange, auth);
            String key = requireIdempotencyKey(exchange.getRequestHeaders());
            await(idempotency.execute(
                    auth.principal().accountId(),
                    method,
                    path,
                    key,
                    fingerprint(method, path, null),
                    () -> {
                        authentication.logout(auth.principal());
                        return java.util.concurrent.CompletableFuture.completedFuture(null);
                    }));
            expireSessionCookie(exchange.getResponseHeaders());
            respondEmpty(exchange, 204);
        } else if (method.equals("GET") && path.equals("/api/v1/auth/sessions")) {
            respondJson(exchange, 200, authentication.sessions(auth.principal()));
        } else if (method.equals("DELETE") && path.startsWith("/api/v1/auth/sessions/")) {
            requireMutationSecurity(exchange, auth);
            UUID sessionId = parseSessionId(path);
            String key = requireIdempotencyKey(exchange.getRequestHeaders());
            await(idempotency.execute(
                    auth.principal().accountId(),
                    method,
                    path,
                    key,
                    fingerprint(method, path, null),
                    () -> {
                        authentication.revokeSession(auth.principal(), sessionId);
                        return java.util.concurrent.CompletableFuture.completedFuture(null);
                    }));
            if (sessionId.equals(auth.principal().sessionId())) {
                expireSessionCookie(exchange.getResponseHeaders());
            }
            respondEmpty(exchange, 204);
        } else if (method.equals("POST") && path.equals("/api/v1/auth/totp/enrollment")) {
            requireMutationSecurity(exchange, auth);
            TotpEnrollmentRequest request = readJson(exchange, TotpEnrollmentRequest.class);
            String key = requireIdempotencyKey(exchange.getRequestHeaders());
            Object result = await(idempotency.execute(
                    auth.principal().accountId(),
                    method,
                    path,
                    key,
                    fingerprint(method, path, request),
                    () -> java.util.concurrent.CompletableFuture.completedFuture(
                            authentication.beginTotpEnrollment(
                                    auth.principal(), passwordChars(request.password())))));
            respondJson(exchange, 200, result);
        } else if (method.equals("POST") && path.equals("/api/v1/auth/totp/confirm")) {
            requireMutationSecurity(exchange, auth);
            TotpConfirmationRequest request = readJson(exchange, TotpConfirmationRequest.class);
            String key = requireIdempotencyKey(exchange.getRequestHeaders());
            Object result = await(idempotency.execute(
                    auth.principal().accountId(),
                    method,
                    path,
                    key,
                    fingerprint(method, path, request),
                    () -> java.util.concurrent.CompletableFuture.completedFuture(Map.of(
                            "recoveryCodes",
                            authentication.confirmTotpEnrollment(
                                    auth.principal(), request.code())))));
            respondJson(exchange, 200, result);
        } else if (method.equals("POST") && path.equals("/api/v1/auth/totp/disable")) {
            requireMutationSecurity(exchange, auth);
            ReauthenticationRequest request = readJson(exchange, ReauthenticationRequest.class);
            String key = requireIdempotencyKey(exchange.getRequestHeaders());
            await(idempotency.execute(auth.principal().accountId(), method, path, key,
                    fingerprint(method, path, request), () -> {
                        authentication.disableTotp(auth.principal(), passwordChars(request.password()), request.secondFactor());
                        return java.util.concurrent.CompletableFuture.completedFuture(null);
                    }));
            respondEmpty(exchange, 204);
        } else if (method.equals("POST") && path.equals("/api/v1/auth/reauthenticate")) {
            requireMutationSecurity(exchange, auth);
            ReauthenticationRequest request = readJson(exchange, ReauthenticationRequest.class);
            String key = requireIdempotencyKey(exchange.getRequestHeaders());
            await(idempotency.execute(
                    auth.principal().accountId(),
                    method,
                    path,
                    key,
                    fingerprint(method, path, request),
                    () -> {
                        if (request.password() == null || request.password().isBlank()) {
                            authentication.reauthenticateWithTotp(auth.principal(), request.secondFactor());
                        } else {
                            authentication.reauthenticate(
                                    auth.principal(),
                                    passwordChars(request.password()),
                                    request.secondFactor());
                        }
                        return java.util.concurrent.CompletableFuture.completedFuture(null);
                    }));
            respondEmpty(exchange, 204);
        } else if (method.equals("GET") && path.equals("/api/v1/accounts")) {
            requireCapability(auth.principal(), Capability.ACCOUNT_MANAGE);
            respondJson(exchange, 200, authentication.accounts(auth.principal()));
        } else if (method.equals("POST") && path.equals("/api/v1/accounts")) {
            requireAccountMutationSecurity(exchange, auth);
            AccountCreationRequest request = readJson(exchange, AccountCreationRequest.class);
            Role role = requiredRole(request.role());
            String key = requireIdempotencyKey(exchange.getRequestHeaders());
            Object result = await(idempotency.execute(
                    auth.principal().accountId(),
                    method,
                    path,
                    key,
                    fingerprint(method, path, request),
                    () -> auditedAccountMutation(
                            auth.principal(),
                            "account.create",
                            newAccountAuditTarget(request.username()),
                            () -> null,
                            requestId,
                            () -> authentication.createAccount(
                                    auth.principal(),
                                    request.username(),
                                    passwordChars(request.password()),
                                    role))));
            respondJson(exchange, 201, result);
        } else if (method.equals("PATCH") && path.startsWith("/api/v1/accounts/")) {
            requireAccountMutationSecurity(exchange, auth);
            UUID accountId = parseAccountId(path);
            AccountPatchRequest request = readJson(exchange, AccountPatchRequest.class);
            Role role = optionalRole(request.role());
            String key = requireIdempotencyKey(exchange.getRequestHeaders());
            Object result = await(idempotency.execute(
                    auth.principal().accountId(),
                    method,
                    path,
                    key,
                    fingerprint(method, path, request),
                    () -> auditedAccountMutation(
                            auth.principal(),
                            "account.update",
                            accountId.toString(),
                            () -> authentication.account(auth.principal(), accountId),
                            requestId,
                            () -> authentication.updateAccount(
                                    auth.principal(), accountId, role, request.disabled()))));
            if (accountId.equals(auth.principal().accountId())
                    && (Boolean.TRUE.equals(request.disabled())
                            || (role != null && role != auth.principal().role()))) {
                expireSessionCookie(exchange.getResponseHeaders());
            }
            respondJson(exchange, 200, result);
        } else if (method.equals("DELETE") && path.startsWith("/api/v1/accounts/")) {
            requireAccountMutationSecurity(exchange, auth);
            UUID accountId = parseAccountId(path);
            String key = requireIdempotencyKey(exchange.getRequestHeaders());
            await(idempotency.execute(
                    auth.principal().accountId(),
                    method,
                    path,
                    key,
                    fingerprint(method, path, null),
                    () -> auditedAccountMutation(
                            auth.principal(),
                            "account.delete",
                            accountId.toString(),
                            () -> authentication.account(auth.principal(), accountId),
                            requestId,
                            () -> {
                                authentication.deleteAccount(auth.principal(), accountId);
                                return null;
                            })));
            if (accountId.equals(auth.principal().accountId())) {
                expireSessionCookie(exchange.getResponseHeaders());
            }
            respondEmpty(exchange, 204);
        } else if (method.equals("GET") && path.equals("/api/v1/status")) {
            requireCapability(auth.principal(), Capability.STATUS_READ);
            respondGateway(exchange, gateway.status(auth.principal()), 200);
        } else if (method.equals("GET") && path.equals("/api/v1/players")) {
            requireCapability(auth.principal(), Capability.PLAYER_READ);
            respondGateway(
                    exchange,
                    gateway.players(auth.principal(), query(exchange.getRequestURI())),
                    200);
        } else if (method.equals("GET") && path.equals("/api/v1/audit")) {
            requireCapability(auth.principal(), Capability.AUDIT_READ);
            respondGateway(
                    exchange, gateway.audit(auth.principal(), query(exchange.getRequestURI())), 200);
        } else if (method.equals("POST") && path.equals("/api/v1/operations")) {
            requireMutationSecurity(exchange, auth);
            requireCapability(auth.principal(), Capability.PLAYER_DESTRUCTIVE_WRITE);
            var request = readJson(exchange, ManagementGateway.OperationRequest.class);
            String key = requireIdempotencyKey(exchange.getRequestHeaders());
            respondGateway(exchange, idempotency.execute(
                    auth.principal().accountId(),
                    method,
                    path,
                    key,
                    fingerprint(method, path, request),
                    () -> gateway.submitOperation(auth.principal(), request, requestId, key)), 202);
        } else if (method.equals("GET") && path.equals("/api/v1/features")) {
            requireCapability(auth.principal(), Capability.STATUS_READ);
            respondJson(exchange, 200, featureFlags());
        } else if (method.equals("GET") && path.equals("/api/v1/settings")) {
            requireCapability(auth.principal(), Capability.STATUS_READ);
            respondJson(exchange, 200, publicSettings());
        } else if (method.equals("PUT") && path.equals("/api/v1/settings")) {
            requireMutationSecurity(exchange, auth);
            requireCapability(auth.principal(), Capability.SETTINGS_WRITE);
            if (auth.principal().role() != Role.OWNER) {
                throw new ForbiddenException("owner role is required to edit server configuration");
            }
            requireRecentStrongAuthentication(auth);
            Object request = readJson(exchange, Object.class);
            String key = requireIdempotencyKey(exchange.getRequestHeaders());
            Object result = await(idempotency.execute(
                    auth.principal().accountId(), method, path, key,
                    fingerprint(method, path, request),
                    () -> gateway.request(auth.principal(), new ManagementGateway.ApiRequest(
                            method, "/settings", Map.of(), request, requestId, key))));
            rememberPendingSettings(request);
            respondJson(exchange, 202, result);
        } else if (path.equals("/api/v1/settings")) {
            exchange.getResponseHeaders().set("Allow", "GET, PUT");
            problem(exchange, 405, "Method not allowed", "use PUT to replace startup configuration", requestId);
        } else if (method.equals("POST")
                && (path.equals("/api/v1/console") || path.equals("/api/v1/console/commands"))) {
            requireMutationSecurity(exchange, auth);
            requireCapability(auth.principal(), Capability.CONSOLE_EXECUTE);
            if (!gateway.featureAvailable("console")) {
                throw new ForbiddenException("web console is disabled in server configuration");
            }
            requireRecentStrongAuthentication(auth);
            var request = readJson(exchange, ManagementGateway.ConsoleRequest.class);
            String key = requireIdempotencyKey(exchange.getRequestHeaders());
            respondGateway(exchange, idempotency.execute(
                    auth.principal().accountId(),
                    method,
                    path,
                    key,
                    fingerprint(method, path, request),
                    () -> gateway.executeConsole(auth.principal(), request, requestId, key)), 202);
        } else if (method.equals("GET") && path.equals("/api/v1/events")) {
            requireCapability(auth.principal(), Capability.STATUS_READ);
            handleSse(exchange, auth.rawSessionToken());
        } else if (isExtendedRoute(method, path)) {
            handleExtendedRoute(exchange, auth, method, path, requestId);
        } else {
            problem(exchange, 404, "Not found", "the requested resource does not exist", requestId);
        }
    }

    private void handleSetup(HttpExchange exchange) throws IOException {
        SetupRequest request = readJson(exchange, SetupRequest.class);
        String path = normalizedPath(exchange.getRequestURI());
        String key = requireIdempotencyKey(exchange.getRequestHeaders());
        var issued = (com.xfestudio.xfeservermanager.infra.security.IssuedSession) await(
                idempotency.execute(
                        ANONYMOUS_IDEMPOTENCY_SCOPE,
                        "POST",
                        path,
                        key,
                        fingerprint("POST", path, request),
                        () -> java.util.concurrent.CompletableFuture.completedFuture(
                                authentication.createInitialOwner(
                                        request.bootstrapToken(),
                                        request.username(),
                                        passwordChars(request.password()),
                                        remoteAddress(exchange),
                                        exchange.getRequestHeaders().getFirst("User-Agent")))));
        setSessionCookie(exchange.getResponseHeaders(), issued.sessionToken(), issued.expiresAt());
        respondJson(exchange, 201, sessionResponse(issued.principal(), issued.csrfToken()));
    }

    private void handleLogin(HttpExchange exchange) throws IOException {
        LoginRequest request = readJson(exchange, LoginRequest.class);
        String path = normalizedPath(exchange.getRequestURI());
        String key = requireIdempotencyKey(exchange.getRequestHeaders());
        var issued = (com.xfestudio.xfeservermanager.infra.security.IssuedSession) await(
                idempotency.execute(
                        ANONYMOUS_IDEMPOTENCY_SCOPE,
                        "POST",
                        path,
                        key,
                        fingerprint("POST", path, request),
                        () -> java.util.concurrent.CompletableFuture.completedFuture(
                                authentication.login(
                                        request.username(),
                                        passwordChars(request.password()),
                                        request.secondFactor(),
                                        remoteAddress(exchange),
                                        exchange.getRequestHeaders().getFirst("User-Agent")))));
        setSessionCookie(exchange.getResponseHeaders(), issued.sessionToken(), issued.expiresAt());
        respondJson(exchange, 200, sessionResponse(issued.principal(), issued.csrfToken()));
    }

    private void handleSession(HttpExchange exchange) throws IOException {
        Optional<String> token = cookie(exchange.getRequestHeaders(), SESSION_COOKIE);
        if (token.isPresent()) {
            Optional<AuthenticatedPrincipal> principal = authentication.authenticate(token.get());
            if (principal.isPresent()) {
                respondJson(exchange, 200, sessionResponse(
                        principal.get(), authentication.csrfToken(token.get())));
                return;
            }
        }
        respondJson(exchange, 200, Map.of(
                "authenticated", false,
                "bootstrapRequired", ownerSetupRequired()));
    }

    private void handleSse(HttpExchange exchange, String rawSessionToken)
            throws IOException, InterruptedException {
        long after = parseLastEventId(exchange.getRequestHeaders().getFirst("Last-Event-ID"));
        SseBroker.Subscription subscription = events.subscribe(after)
                .orElseThrow(() -> new ServiceUnavailableException("too many event subscribers"));
        Headers headers = exchange.getResponseHeaders();
        headers.set("Content-Type", "text/event-stream; charset=utf-8");
        headers.set("Cache-Control", "no-cache, no-transform");
        headers.set("X-Accel-Buffering", "no");
        exchange.sendResponseHeaders(200, 0);
        try (subscription; var output = exchange.getResponseBody()) {
            output.write(": connected\n\n".getBytes(StandardCharsets.UTF_8));
            output.flush();
            long nextSessionCheck = System.nanoTime();
            while (subscription.isOpen() && state.get() == State.RUNNING) {
                long now = System.nanoTime();
                if (now - nextSessionCheck >= 0) {
                    if (!isSessionActive(rawSessionToken)) {
                        break;
                    }
                    nextSessionCheck = now + SSE_SESSION_RECHECK_NANOS;
                }
                long untilSessionCheck = Math.max(1L, nextSessionCheck - System.nanoTime());
                Optional<SseBroker.Event> event = subscription.poll(
                        Duration.ofNanos(Math.min(SSE_SESSION_RECHECK_NANOS, untilSessionCheck)));
                if (event.isPresent()) {
                    output.write(event.get().encode().getBytes(StandardCharsets.UTF_8));
                } else {
                    output.write(": heartbeat\n\n".getBytes(StandardCharsets.UTF_8));
                }
                output.flush();
            }
        }
    }

    boolean isSessionActive(String rawSessionToken) {
        try {
            return authentication.authenticate(rawSessionToken).isPresent();
        } catch (RuntimeException unavailable) {
            return false;
        }
    }

    private void handleMetrics(HttpExchange exchange) throws IOException {
        if (!configuration.metricsEnabled()) {
            throw new NotFoundException("metrics endpoint is disabled");
        }
        String authorization = exchange.getRequestHeaders().getFirst("Authorization");
        String supplied = authorization != null && authorization.startsWith("Bearer ")
                ? authorization.substring("Bearer ".length())
                : "";
        if (metricsToken.isEmpty() || supplied.length() < 32 || supplied.length() > 256
                || !SecureTokenComparison.matches(metricsToken, supplied)) {
            exchange.getResponseHeaders().set("WWW-Authenticate", "Bearer");
            throw new AuthenticationException("unauthenticated", "a valid metrics token is required");
        }
        var snapshot = gateway.metricsSnapshot();
        if (snapshot == null || !gateway.serverReady()) {
            throw new ServiceUnavailableException("server metrics are not ready");
        }
        byte[] encoded = metricsFormatter.format(snapshot).getBytes(StandardCharsets.UTF_8);
        exchange.getResponseHeaders().set(
                "Content-Type", "application/openmetrics-text; version=1.0.0; charset=utf-8");
        exchange.sendResponseHeaders(200, encoded.length);
        exchange.getResponseBody().write(encoded);
    }

    private AuthContext requireAuthentication(HttpExchange exchange) {
        String token = cookie(exchange.getRequestHeaders(), SESSION_COOKIE)
                .orElseThrow(() -> new AuthenticationException("unauthenticated", "sign in is required"));
        AuthenticatedPrincipal principal = authentication.authenticate(token)
                .orElseThrow(() -> new AuthenticationException("unauthenticated", "session is invalid or expired"));
        return new AuthContext(principal, token);
    }

    private void requireMutationSecurity(HttpExchange exchange, AuthContext auth) {
        requirePublicOrigin(exchange);
        String csrf = exchange.getRequestHeaders().getFirst("X-CSRF-Token");
        if (!authentication.verifyCsrf(auth.rawSessionToken(), csrf)) {
            throw new ForbiddenException("CSRF token is invalid");
        }
    }

    private void requireAccountMutationSecurity(HttpExchange exchange, AuthContext auth) {
        requireMutationSecurity(exchange, auth);
        requireCapability(auth.principal(), Capability.ACCOUNT_MANAGE);
        requireRecentStrongAuthentication(auth);
    }

    /** Executes only after a durable admission event and caches failures through idempotency. */
    java.util.concurrent.CompletionStage<AuthenticationService.AccountView> auditedAccountMutation(
                    AuthenticatedPrincipal principal,
                    String action,
                    String target,
                    Supplier<AuthenticationService.AccountView> beforeLoader,
                    String requestId,
                    Supplier<AuthenticationService.AccountView> mutation) {
        java.util.concurrent.CompletableFuture<AuthenticationService.AccountView> result =
                new java.util.concurrent.CompletableFuture<>();
        AuditEvent admission = accountAuditEvent(
                principal,
                action,
                target,
                requestId,
                Map.of(),
                Map.of(),
                AuditOutcome.SUCCEEDED,
                0,
                Map.of("phase", "admission", "result", "admitted"));
        try {
            await(gateway.appendSecurityAudit(admission));
        } catch (RuntimeException auditFailure) {
            result.completeExceptionally(securityAuditUnavailable(auditFailure));
            return result;
        }

        long started = System.nanoTime();
        Map<String, String> beforeValues = Map.of();
        AuthenticationService.AccountView value;
        try {
            beforeValues = accountAuditValues(beforeLoader.get());
            value = mutation.get();
        } catch (RuntimeException mutationFailure) {
            AuditEvent completion = accountAuditEvent(
                    principal,
                    action,
                    target,
                    requestId,
                    beforeValues,
                    Map.of(),
                    AuditOutcome.FAILED,
                    elapsedMillis(started),
                    Map.of(
                            "phase", "completion",
                            "result", "failed",
                            "errorType", mutationFailure.getClass().getSimpleName()));
            try {
                await(gateway.appendSecurityAudit(completion));
                result.completeExceptionally(mutationFailure);
            } catch (RuntimeException auditFailure) {
                ServiceUnavailableException unavailable = securityAuditUnavailable(auditFailure);
                unavailable.addSuppressed(mutationFailure);
                result.completeExceptionally(unavailable);
            }
            return result;
        }

        String completionTarget = value == null ? target : value.id().toString();
        AuditEvent completion = accountAuditEvent(
                principal,
                action,
                completionTarget,
                requestId,
                beforeValues,
                accountAuditValues(value),
                AuditOutcome.SUCCEEDED,
                elapsedMillis(started),
                Map.of("phase", "completion", "result", "succeeded"));
        try {
            await(gateway.appendSecurityAudit(completion));
            result.complete(value);
        } catch (RuntimeException auditFailure) {
            result.completeExceptionally(securityAuditUnavailable(auditFailure));
        }
        return result;
    }

    private static AuditEvent accountAuditEvent(
            AuthenticatedPrincipal principal,
            String action,
            String target,
            String requestId,
            Map<String, String> before,
            Map<String, String> after,
            AuditOutcome outcome,
            long durationMillis,
            Map<String, String> metadata) {
        return new AuditEvent(
                UUID.randomUUID(),
                Instant.now(),
                principal.accountId().toString(),
                principal.username(),
                CommandSourceKind.WEB_CONSOLE,
                action,
                target,
                "",
                before,
                after,
                null,
                requestId,
                outcome,
                durationMillis,
                metadata);
    }

    private static Map<String, String> accountAuditValues(
            AuthenticationService.AccountView account) {
        if (account == null) {
            return Map.of();
        }
        Map<String, String> values = new LinkedHashMap<>();
        values.put("id", account.id().toString());
        values.put("username", account.username());
        values.put("role", account.role());
        values.put("totpEnabled", Boolean.toString(account.totpEnabled()));
        values.put("disabled", Boolean.toString(account.disabled()));
        values.put("createdAt", account.createdAt().toString());
        values.put("updatedAt", account.updatedAt().toString());
        values.put("lastLoginAt", account.lastLoginAt() == null
                ? ""
                : account.lastLoginAt().toString());
        return Map.copyOf(values);
    }

    private static String newAccountAuditTarget(String username) {
        if (username == null) {
            return "new-account";
        }
        String safe = username.strip();
        return safe.matches("[A-Za-z0-9_.-]{3,32}") ? "username:" + safe : "new-account";
    }

    private static long elapsedMillis(long startedNanos) {
        return TimeUnit.NANOSECONDS.toMillis(Math.max(0, System.nanoTime() - startedNanos));
    }

    private static ServiceUnavailableException securityAuditUnavailable(Throwable cause) {
        return new ServiceUnavailableException("security audit is unavailable", cause);
    }

    private void requirePublicOrigin(HttpExchange exchange) {
        String origin = exchange.getRequestHeaders().getFirst("Origin");
        if (origin == null || !normalizeOrigin(configuration.publicBaseUrl()).equals(normalizeOrigin(origin))) {
            throw new ForbiddenException("request origin is not allowed");
        }
    }

    private static void requireCapability(AuthenticatedPrincipal principal, Capability capability) {
        if (!principal.permits(capability)) {
            throw new ForbiddenException("missing capability " + capability.name().toLowerCase(Locale.ROOT));
        }
    }

    private void handleExtendedRoute(
            HttpExchange exchange,
            AuthContext auth,
            String method,
            String path,
            String requestId) throws IOException {
        boolean requestMutation = !method.equals("GET") && !method.equals("HEAD");
        boolean validationOnly = method.equals("POST") && path.equals("/api/v1/triggers/validate");
        boolean stateMutation = extendedStateMutation(method, path);
        // Content media has a separate bounded upload envelope; no other JSON route gets it.
        boolean contentUpload = method.equals("POST") && path.equals("/api/v1/content/assets");
        if (contentUpload) {
            requireCapability(auth.principal(), Capability.CONSOLE_EXECUTE);
            requireRecentStrongAuthentication(auth);
        }
        String idempotencyKey = "";
        Object body = null;
        if (requestMutation) {
            requireMutationSecurity(exchange, auth);
            if (stateMutation) {
                idempotencyKey = requireIdempotencyKey(exchange.getRequestHeaders());
            }
            if (hasRequestBody(exchange.getRequestHeaders())) {
                body = readJson(exchange, Object.class,
                        contentUpload ? 12 * 1024 * 1024
                                : validationOnly ? MAXIMUM_TRIGGER_VALIDATION_JSON_BYTES : MAXIMUM_JSON_BYTES);
            }
        }
        Capability capability = extendedCapability(method, path, body);
        requireCapability(auth.principal(), capability);
        if (stateMutation && requiresStrongAuthentication(capability)) {
            requireRecentStrongAuthentication(auth);
        }
        ManagementGateway.ApiRequest request = new ManagementGateway.ApiRequest(
                method,
                path.substring("/api/v1".length()),
                query(exchange.getRequestURI()),
                body,
                requestId,
                idempotencyKey);
        var stage = stateMutation
                ? idempotency.execute(
                        auth.principal().accountId(),
                        method,
                        path,
                        idempotencyKey,
                        fingerprint(method, path, body),
                        () -> gateway.request(auth.principal(), request))
                : gateway.request(auth.principal(), request);
        respondGateway(exchange, stage, extendedSuccessStatus(method, path));
    }

    private static boolean isExtendedRoute(String method, String path) {
        if (!SetOfMethods.SUPPORTED.contains(method)) {
            return false;
        }
        return hasResourcePrefix(path, "/api/v1/players")
                || hasResourcePrefix(path, "/api/v1/policies")
                || hasResourcePrefix(path, "/api/v1/operations")
                || hasResourcePrefix(path, "/api/v1/moderation")
                || hasResourcePrefix(path, "/api/v1/maintenance")
                || hasResourcePrefix(path, "/api/v1/triggers")
                || hasResourcePrefix(path, "/api/v1/trigger-groups")
                || hasResourcePrefix(path, "/api/v1/trigger-executions")
                || hasResourcePrefix(path, "/api/v1/trigger-event-captures")
                || hasResourcePrefix(path, "/api/v1/trigger-event-samples")
                || hasResourcePrefix(path, "/api/v1/trigger-libraries")
                || hasResourcePrefix(path, "/api/v1/menus")
                || hasResourcePrefix(path, "/api/v1/menu-assets")
                || hasResourcePrefix(path, "/api/v1/economy")
                || hasResourcePrefix(path, "/api/v1/content")
                || hasResourcePrefix(path, "/api/v1/claims")
                || hasResourcePrefix(path, "/api/v1/world")
                || hasResourcePrefix(path, "/api/v1/rollbacks");
    }

    private static boolean hasResourcePrefix(String path, String prefix) {
        return path.equals(prefix) || path.startsWith(prefix + '/');
    }

    private static boolean requiresStrongAuthentication(Capability capability) {
        return switch (capability) {
            case PLAYER_DESTRUCTIVE_WRITE, INVENTORY_WRITE, MODERATION_WRITE, POLICY_PUBLISH,
                    SETTINGS_WRITE, ACCOUNT_MANAGE, CONSOLE_EXECUTE, CLAIM_MANAGE,
                    MAINTENANCE_MANAGE, TRIGGER_WRITE, MENU_WRITE,
                    ECONOMY_MANAGE,
                    WORLD_ROLLBACK, WORLD_FORCE_ROLLBACK -> true;
            default -> false;
        };
    }

    private void requireRecentStrongAuthentication(AuthContext auth) {
        if (!authentication.hasRequiredSecondFactor(auth.principal())
                || !authentication.recentlyAuthenticated(auth.principal())) {
            throw new ReauthenticationRequiredException(authentication.isTotpEnabled(auth.principal())
                    ? "recent TOTP verification is required" : "recent password verification is required");
        }
    }

    static Capability extendedCapability(String method, String path, Object body) {
        boolean read = method.equals("GET") || method.equals("HEAD");
        if (hasResourcePrefix(path, "/api/v1/content")) {
            // Content can change registration, collisions, combat and client assets. Keep
            // publication and editing owner-only, independently of the console feature toggle.
            return read || method.equals("POST") && path.equals("/api/v1/content/validate")
                    ? Capability.TRIGGER_READ : Capability.CONSOLE_EXECUTE;
        }
        if (path.equals("/api/v1/triggers/validate")) {
            return Capability.TRIGGER_READ;
        }
        if (hasResourcePrefix(path, "/api/v1/players")) {
            if (path.contains("/inventory") || path.contains("/ender-chest")) {
                return Capability.INVENTORY_WRITE;
            }
            if (!read && path.endsWith("/actions")
                    && body instanceof Map<?, ?> values
                    && "message".equalsIgnoreCase(
                            Objects.toString(values.get("action"), "").strip())) {
                return Capability.PLAYER_MESSAGE;
            }
            return read ? Capability.PLAYER_READ : Capability.PLAYER_SAFE_WRITE;
        }
        if (hasResourcePrefix(path, "/api/v1/policies")) {
            return path.endsWith("/publish") ? Capability.POLICY_PUBLISH : Capability.POLICY_EDIT;
        }
        if (hasResourcePrefix(path, "/api/v1/operations")) {
            // Operation documents can contain inventory/policy result details. The global SSE
            // carries a separately redacted lifecycle projection for status-only roles.
            return Capability.PLAYER_DESTRUCTIVE_WRITE;
        }
        if (hasResourcePrefix(path, "/api/v1/moderation")) {
            return read ? Capability.AUDIT_READ : Capability.MODERATION_WRITE;
        }
        if (hasResourcePrefix(path, "/api/v1/claims")) {
            return read ? Capability.CLAIM_READ : Capability.CLAIM_MANAGE;
        }
        if (hasResourcePrefix(path, "/api/v1/world")) {
            return read ? Capability.WORLD_QUERY : Capability.WORLD_ROLLBACK;
        }
        if (hasResourcePrefix(path, "/api/v1/rollbacks")) {
            return read ? Capability.WORLD_QUERY : Capability.WORLD_ROLLBACK;
        }
        if (hasResourcePrefix(path, "/api/v1/maintenance")) {
            return Capability.MAINTENANCE_MANAGE;
        }
        if (hasResourcePrefix(path, "/api/v1/triggers")
                || hasResourcePrefix(path, "/api/v1/trigger-groups")
                || hasResourcePrefix(path, "/api/v1/trigger-executions")
                || hasResourcePrefix(path, "/api/v1/trigger-event-captures")
                || hasResourcePrefix(path, "/api/v1/trigger-event-samples")
                || hasResourcePrefix(path, "/api/v1/trigger-libraries")) {
            return read ? Capability.TRIGGER_READ : Capability.TRIGGER_WRITE;
        }
        if (hasResourcePrefix(path, "/api/v1/menus")
                || hasResourcePrefix(path, "/api/v1/menu-assets")) {
            return read ? Capability.MENU_READ : Capability.MENU_WRITE;
        }
        if (hasResourcePrefix(path, "/api/v1/economy")) {
            return read ? Capability.ECONOMY_READ : Capability.ECONOMY_MANAGE;
        }
        return Capability.STATUS_READ;
    }

    static int extendedSuccessStatus(String method, String path) {
        if (method.equals("GET") || method.equals("HEAD")
                || path.endsWith("/validate")
                || path.endsWith("/simulate") || path.endsWith("/preview")
                || (method.equals("PATCH") && path.matches("/api/v1/triggers/[^/]+/state"))) {
            return 200;
        }
        return 202;
    }

    static boolean extendedStateMutation(String method, String path) {
        return !method.equals("GET") && !method.equals("HEAD")
                && !(method.equals("POST") && (path.equals("/api/v1/triggers/validate")
                    || path.equals("/api/v1/content/validate")));
    }

    private static String requireIdempotencyKey(Headers headers) {
        String key = headers.getFirst("Idempotency-Key");
        if (key == null || !key.matches("[A-Za-z0-9._:-]{8,128}")) {
            throw new IllegalArgumentException(
                    "Idempotency-Key must contain 8-128 safe ASCII characters");
        }
        return key;
    }

    private static boolean hasRequestBody(Headers headers) {
        long length = contentLength(headers);
        return length > 0 || (length < 0 && headers.getFirst("Transfer-Encoding") != null);
    }

    private void respondGateway(HttpExchange exchange, java.util.concurrent.CompletionStage<?> stage, int status)
            throws IOException {
        Object result = await(stage);
        respondJson(exchange, status, result);
    }

    static Object await(java.util.concurrent.CompletionStage<?> stage) {
        try {
            // Do not use CompletableFuture.orTimeout here: it completes the gateway's actual
            // future exceptionally while the already queued Minecraft-thread mutation can still
            // run. Leaving the future pending lets an idempotent retry observe the one eventual
            // result instead of caching a false timeout failure.
            return stage.toCompletableFuture().get(GATEWAY_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
        } catch (InterruptedException interrupted) {
            Thread.currentThread().interrupt();
            throw new CompletionException(interrupted);
        } catch (java.util.concurrent.ExecutionException failure) {
            throw new CompletionException(failure.getCause());
        } catch (TimeoutException pending) {
            throw new CompletionException(pending);
        }
    }

    private <T> T readJson(HttpExchange exchange, Class<T> type) throws IOException {
        return readJson(exchange, type, MAXIMUM_JSON_BYTES);
    }

    private <T> T readJson(HttpExchange exchange, Class<T> type, int maximumBytes) throws IOException {
        return json.read(
                exchange.getRequestBody(),
                type,
                contentLength(exchange.getRequestHeaders()),
                maximumBytes);
    }

    private void respondJson(HttpExchange exchange, int status, Object body) throws IOException {
        byte[] encoded = json.writeBytes(body);
        exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
        exchange.sendResponseHeaders(status, encoded.length);
        exchange.getResponseBody().write(encoded);
    }

    private static void respondEmpty(HttpExchange exchange, int status) throws IOException {
        exchange.sendResponseHeaders(status, -1);
    }

    private void problem(HttpExchange exchange, int status, String title, String detail, String requestId)
            throws IOException {
        byte[] encoded = json.writeBytes(ProblemDetails.of(status, title, detail, requestId));
        exchange.getResponseHeaders().set(
                "Content-Type", "application/problem+json; charset=utf-8");
        exchange.sendResponseHeaders(status, encoded.length);
        exchange.getResponseBody().write(encoded);
    }

    private void serveStatic(HttpExchange exchange, String path) throws IOException {
        String resource = path.equals("/") ? "web/index.html" : "web" + path;
        if (resource.contains("..")) {
            throw new IllegalArgumentException("invalid static resource path");
        }
        byte[] bytes;
        try (var input = HttpApiServer.class.getClassLoader().getResourceAsStream(resource)) {
            if (input == null) {
                if (!path.contains(".")) {
                    serveStatic(exchange, "/");
                    return;
                }
                throw new NotFoundException("static resource does not exist");
            }
            bytes = input.readNBytes(2 * 1024 * 1024 + 1);
        }
        if (bytes.length > 2 * 1024 * 1024) {
            throw new IllegalArgumentException("static resource is too large");
        }
        exchange.getResponseHeaders().set("Content-Type", contentType(resource));
        exchange.getResponseHeaders().set(
                "Cache-Control", resource.endsWith("index.html") ? "no-cache" : "public, max-age=31536000, immutable");
        exchange.sendResponseHeaders(200, bytes.length);
        exchange.getResponseBody().write(bytes);
    }

    private void setSessionCookie(Headers headers, String token, java.time.Instant expiresAt) {
        StringBuilder value = new StringBuilder(SESSION_COOKIE).append('=').append(token)
                .append("; Path=/; HttpOnly; SameSite=Strict; Max-Age=")
                .append(Math.max(0, Duration.between(java.time.Instant.now(), expiresAt).toSeconds()));
        if (isSecurePublicOrigin()) {
            value.append("; Secure");
        }
        headers.add("Set-Cookie", value.toString());
    }

    private void expireSessionCookie(Headers headers) {
        String value = SESSION_COOKIE + "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0";
        if (isSecurePublicOrigin()) {
            value += "; Secure";
        }
        headers.add("Set-Cookie", value);
    }

    private static Optional<String> cookie(Headers headers, String name) {
        for (String line : headers.getOrDefault("Cookie", java.util.List.of())) {
            for (String part : line.split(";")) {
                String[] pair = part.strip().split("=", 2);
                if (pair.length == 2 && pair[0].equals(name)) {
                    return Optional.of(pair[1]);
                }
            }
        }
        return Optional.empty();
    }

    private Map<String, Object> sessionResponse(
            AuthenticatedPrincipal principal, String csrfToken) {
        Map<String, Object> actor = Map.of(
                "id", principal.accountId().toString(),
                "displayName", principal.username(),
                "roles", java.util.List.of(principal.role().wireName()),
                "permissions", principal.role().capabilities().stream()
                        .map(value -> value.name().toLowerCase(Locale.ROOT))
                        .sorted()
                        .toList(),
                "totpEnabled", authentication.isTotpEnabled(principal),
                "totpVerified", principal.secondFactorVerified(),
                "reauthenticationRequired", !authentication.hasRequiredSecondFactor(principal)
                        || !authentication.recentlyAuthenticated(principal));
        Map<String, Object> response = new LinkedHashMap<>();
        response.put("authenticated", true);
        response.put("actor", actor);
        response.put("csrfToken", csrfToken);
        response.put("bootstrapRequired", false);
        response.put("expiresAt", principal.expiresAt().toString());
        return Map.copyOf(response);
    }

    private Map<String, Object> featureFlags() {
        return Map.of(
                "consoleEnabled", gateway.featureAvailable("console"),
                "moderationEnabled", gateway.featureAvailable("moderation"),
                "claimsEnabled", gateway.featureAvailable("claims"),
                "worldTrackingEnabled", gateway.featureAvailable("world-tracking"),
                "rollbackEnabled", gateway.featureAvailable("rollback"),
                "joinExperienceEnabled", gateway.featureAvailable("join-experience"),
                "metricsEnabled", configuration.metricsEnabled());
    }

    private Map<String, Object> publicSettings() {
        Map<String, Object> settings = new LinkedHashMap<>();
        settings.put("bindAddress", configuration.bindAddress().getHostAddress());
        settings.put("port", configuration.port());
        settings.put("publicBaseUrl", configuration.publicBaseUrl());
        settings.put("trustedProxyCidrs", configuration.trustedProxyCidrs());
        settings.put("idleSessionSeconds", configuration.idleSessionTimeout().toSeconds());
        settings.put("absoluteSessionSeconds", configuration.absoluteSessionTimeout().toSeconds());
        settings.put("recentAuthenticationSeconds", configuration.recentAuthenticationWindow().toSeconds());
        settings.put("httpThreads", configuration.httpThreads());
        settings.put("maximumSseClients", configuration.maximumSseClients());
        settings.put("webConsoleEnabled", configuration.webConsoleEnabled());
        settings.put("rawItemEditingEnabled", configuration.rawItemEditingEnabled());
        settings.put("metricsEnabled", configuration.metricsEnabled());
        settings.put("moderationEnabled", configuration.moderationEnabled());
        settings.put("claimsEnabled", configuration.claimsEnabled());
        settings.put("worldTrackingEnabled", configuration.worldTrackingEnabled());
        settings.put("rollbackEnabled", configuration.rollbackEnabled());
        settings.put("joinExperienceEnabled", configuration.joinExperienceEnabled());
        settings.put("defaultMessageSender", configuration.defaultMessageSender());
        settings.put("joinWelcomeEnabled", configuration.joinWelcomeEnabled());
        settings.put("joinWelcomeMessage", configuration.joinWelcomeMessage());
        settings.put("firstJoinMessageEnabled", configuration.firstJoinMessageEnabled());
        settings.put("firstJoinMessage", configuration.firstJoinMessage());
        settings.put("dailyAnnouncementsEnabled", configuration.dailyAnnouncementsEnabled());
        settings.put("dailyAnnouncements", configuration.dailyAnnouncements());
        settings.put("announcementTimeZone", configuration.announcementTimeZone());
        settings.put("rulesReminderEnabled", configuration.rulesReminderEnabled());
        settings.put("rulesMessage", configuration.rulesMessage());
        settings.put("maintenanceJoinReminderEnabled", configuration.maintenanceJoinReminderEnabled());
        // Keep the base response complete for test/embedded gateways. A live Forge gateway may
        // replace this value with the atomically hot-published configuration below.
        settings.put("crashProtection", configuration.crashProtection());
        settings.putAll(gateway.liveSettings());
        settings.putAll(pendingSettings.get());
        settings.put("features", featureFlags());
        settings.put("restartRequired", !pendingSettings.get().isEmpty());
        settings.put("serverLocale", "zh-CN");
        settings.put("metricsRequireToken", true);
        settings.put("offlineMode", !gateway.onlineMode());
        settings.put("sparkDetected", gateway.integrationDetected("spark"));
        settings.put("blueMapDetected", gateway.integrationDetected("bluemap"));
        return Map.copyOf(settings);
    }

    private void rememberPendingSettings(Object request) {
        if (!(request instanceof Map<?, ?> values)) {
            return;
        }
        java.util.Set<String> startupOnly = java.util.Set.of(
                "bindAddress", "port", "publicBaseUrl", "trustedProxyCidrs",
                "idleSessionSeconds", "absoluteSessionSeconds", "recentAuthenticationSeconds",
                "httpThreads", "maximumSseClients", "metricsEnabled");
        Map<String, Object> desired = new LinkedHashMap<>(pendingSettings.get());
        values.forEach((key, value) -> {
            String name = Objects.toString(key, "");
            if (startupOnly.contains(name) && value != null) {
                if (matchesStartupSetting(name, value)) desired.remove(name);
                else desired.put(name, value);
            }
        });
        pendingSettings.set(Map.copyOf(desired));
    }

    private boolean matchesStartupSetting(String name, Object value) {
        Object startup = switch (name) {
            case "bindAddress" -> configuration.bindAddress().getHostAddress();
            case "port" -> configuration.port();
            case "publicBaseUrl" -> configuration.publicBaseUrl();
            case "trustedProxyCidrs" -> configuration.trustedProxyCidrs();
            case "idleSessionSeconds" -> configuration.idleSessionTimeout().toSeconds();
            case "absoluteSessionSeconds" -> configuration.absoluteSessionTimeout().toSeconds();
            case "recentAuthenticationSeconds" -> configuration.recentAuthenticationWindow().toSeconds();
            case "httpThreads" -> configuration.httpThreads();
            case "maximumSseClients" -> configuration.maximumSseClients();
            case "metricsEnabled" -> configuration.metricsEnabled();
            default -> null;
        };
        if (startup instanceof Number expected && value instanceof Number supplied) {
            return expected.longValue() == supplied.longValue();
        }
        return Objects.equals(startup, value);
    }

    private static Map<String, String> query(URI uri) {
        Map<String, String> result = new LinkedHashMap<>();
        String raw = uri.getRawQuery();
        if (raw == null || raw.isBlank()) {
            return Map.of();
        }
        for (String pair : raw.split("&", 101)) {
            if (result.size() >= 100) {
                throw new IllegalArgumentException("too many query parameters");
            }
            String[] values = pair.split("=", 2);
            result.put(decode(values[0]), values.length == 2 ? decode(values[1]) : "");
        }
        return Map.copyOf(result);
    }

    private static String decode(String value) {
        return URLDecoder.decode(value, StandardCharsets.UTF_8);
    }

    private static long parseLastEventId(String value) {
        if (value == null || value.isBlank()) {
            return 0;
        }
        try {
            return Math.max(0, Long.parseLong(value));
        } catch (NumberFormatException ignored) {
            return 0;
        }
    }

    private static UUID parseSessionId(String path) {
        String prefix = "/api/v1/auth/sessions/";
        String value = path.substring(prefix.length());
        if (value.isBlank() || value.indexOf('/') >= 0) {
            throw new IllegalArgumentException("invalid session id");
        }
        try {
            return UUID.fromString(value);
        } catch (IllegalArgumentException exception) {
            throw new IllegalArgumentException("invalid session id", exception);
        }
    }

    private static UUID parseAccountId(String path) {
        String prefix = "/api/v1/accounts/";
        String value = path.substring(prefix.length());
        if (value.isBlank() || value.indexOf('/') >= 0) {
            throw new IllegalArgumentException("invalid account id");
        }
        try {
            return UUID.fromString(value);
        } catch (IllegalArgumentException exception) {
            throw new IllegalArgumentException("invalid account id", exception);
        }
    }

    private static Role requiredRole(String value) {
        if (value == null || value.isBlank()) {
            throw new IllegalArgumentException("role is required");
        }
        try {
            return Role.fromWireName(value.strip());
        } catch (IllegalArgumentException exception) {
            throw new IllegalArgumentException("invalid account role", exception);
        }
    }

    private static Role optionalRole(String value) {
        return value == null ? null : requiredRole(value);
    }

    private static String normalizedPath(URI uri) {
        String path = uri.normalize().getPath();
        return path == null || path.isBlank() ? "/" : path;
    }

    private static String requestId(HttpExchange exchange) {
        String supplied = exchange.getRequestHeaders().getFirst("X-Request-ID");
        if (supplied == null) {
            supplied = exchange.getRequestHeaders().getFirst("X-XFESM-Request-ID");
        }
        if (supplied != null && supplied.matches("[A-Za-z0-9._-]{8,64}")) {
            return supplied;
        }
        return UUID.randomUUID().toString();
    }

    private String remoteAddress(HttpExchange exchange) {
        return proxyResolver.resolve(
                exchange.getRemoteAddress().getAddress(), exchange.getRequestHeaders());
    }

    private static long contentLength(Headers headers) {
        String value = headers.getFirst("Content-Length");
        if (value == null) {
            return -1;
        }
        try {
            long parsed = Long.parseLong(value);
            if (parsed < 0) {
                throw new IllegalArgumentException("invalid Content-Length");
            }
            return parsed;
        } catch (NumberFormatException exception) {
            throw new IllegalArgumentException("invalid Content-Length");
        }
    }

    private static String normalizeOrigin(String value) {
        if (value == null) {
            return "";
        }
        try {
            URI uri = URI.create(value.strip());
            if (uri.getHost() == null || uri.getUserInfo() != null || uri.getRawQuery() != null
                    || uri.getRawFragment() != null
                    || (uri.getRawPath() != null && !uri.getRawPath().isEmpty()
                            && !"/".equals(uri.getRawPath()))) {
                return "";
            }
            String rawScheme = uri.getScheme();
            if (rawScheme == null) {
                return "";
            }
            String scheme = rawScheme.toLowerCase(Locale.ROOT);
            if (!scheme.equals("http") && !scheme.equals("https")) {
                return "";
            }
            int port = uri.getPort() >= 0 ? uri.getPort() : (scheme.equals("https") ? 443 : 80);
            return scheme + "://" + uri.getHost().toLowerCase(Locale.ROOT) + ':' + port;
        } catch (IllegalArgumentException exception) {
            return "";
        }
    }

    private String fingerprint(String method, String path, Object body) {
        byte[] digest = com.xfestudio.xfeservermanager.infra.security.SecureTokens.sha256(
                method + '\n' + path + '\n'
                        + new String(json.writeBytes(body), StandardCharsets.UTF_8));
        return HexFormat.of().formatHex(digest);
    }

    private boolean isSecurePublicOrigin() {
        return "https".equalsIgnoreCase(URI.create(configuration.publicBaseUrl()).getScheme());
    }

    private static String contentType(String resource) {
        if (resource.endsWith(".html")) return "text/html; charset=utf-8";
        if (resource.endsWith(".js")) return "text/javascript; charset=utf-8";
        if (resource.endsWith(".css")) return "text/css; charset=utf-8";
        if (resource.endsWith(".svg")) return "image/svg+xml";
        if (resource.endsWith(".png")) return "image/png";
        if (resource.endsWith(".json")) return "application/json; charset=utf-8";
        return "application/octet-stream";
    }

    private static String safeMessage(Throwable throwable) {
        if (throwable == null || throwable.getMessage() == null) {
            return "the operation failed";
        }
        String value = throwable.getMessage().replace('\r', ' ').replace('\n', ' ');
        return value.length() > 200 ? value.substring(0, 200) : value;
    }

    static int domainFailureStatus(Throwable failure) {
        if (failure instanceof com.xfestudio.xfeservermanager.core.content.ContentConflictException) return 409;
        if (failure instanceof PlayerOperationException playerFailure) {
            return switch (playerFailure.code()) {
                case "inventory_revision_conflict", "player_offline" -> 409;
                default -> 400;
            };
        }
        if (failure instanceof PolicyVersionConflictException
                || failure instanceof PolicyDraftConflictException
                || failure instanceof PolicyDraftPresentException) {
            return 409;
        }
        if (failure instanceof TriggerRevisionConflictException
                || failure instanceof TriggerStateRevisionConflictException) {
            return 409;
        }
        if (failure instanceof EconomyConflictException) {
            return 409;
        }
        if (failure instanceof InvalidPolicyException) {
            return 400;
        }
        if (failure instanceof NoPolicyDraftException) {
            return 404;
        }
        if (failure instanceof OperationNotFoundException) {
            return 404;
        }
        if (failure instanceof InvalidOperationTransitionException) {
            return 409;
        }
        return 0;
    }

    private static String domainFailureTitle(int status) {
        return switch (status) {
            case 400 -> "Invalid request";
            case 404 -> "Not found";
            case 409 -> "Conflict";
            default -> "Operation failed";
        };
    }

    private static void applySecurityHeaders(Headers headers, String requestId) {
        // Dynamic management responses may contain account, audit, player, or inventory data.
        // Static resources and SSE replace this value with their route-specific policy.
        headers.set("Cache-Control", "no-store");
        headers.set("X-Content-Type-Options", "nosniff");
        headers.set("X-Frame-Options", "DENY");
        headers.set("Referrer-Policy", "no-referrer");
        headers.set("Permissions-Policy", "camera=(), microphone=(), geolocation=()");
        headers.set("Content-Security-Policy", "default-src 'self'; connect-src 'self'; "
                + "img-src 'self' data:; style-src 'self'; script-src 'self'; frame-ancestors 'none'");
        headers.set("X-Request-ID", requestId);
    }

    private boolean ownerSetupRequired() {
        return authentication.setupRequired();
    }

    @Override
    public synchronized void close() {
        State previous = state.getAndSet(State.STOPPING);
        if (server != null) {
            server.stop(1);
            server = null;
        }
        if (executor != null) {
            executor.shutdownNow();
            executor = null;
        }
        state.set(previous == State.FAILED ? State.FAILED : State.STOPPED);
    }

    public enum State {
        STOPPED,
        STARTING,
        RUNNING,
        STOPPING,
        FAILED
    }

    private record AuthContext(AuthenticatedPrincipal principal, String rawSessionToken) {}

    private record SetupRequest(String bootstrapToken, String username, String password) {}

    private record LoginRequest(
            String username, String password, String totp, String totpCode, String recoveryCode) {
        private String secondFactor() {
            if (totp != null && !totp.isBlank()) return totp;
            if (totpCode != null && !totpCode.isBlank()) return totpCode;
            return recoveryCode;
        }
    }

    private record TotpEnrollmentRequest(String password) {}

    private record TotpConfirmationRequest(String code) {}

    private record ReauthenticationRequest(
            String password, String totp, String totpCode, String recoveryCode) {
        private String secondFactor() {
            if (totp != null && !totp.isBlank()) return totp;
            if (totpCode != null && !totpCode.isBlank()) return totpCode;
            return recoveryCode;
        }
    }

    private record AccountCreationRequest(String username, String password, String role) {}

    private record AccountPatchRequest(String role, Boolean disabled) {}

    private static char[] passwordChars(String password) {
        return password == null ? new char[0] : password.toCharArray();
    }

    private static final class ForbiddenException extends RuntimeException {
        private static final long serialVersionUID = 1L;
        private ForbiddenException(String message) {
            super(message);
        }
    }

    private static final class ReauthenticationRequiredException extends RuntimeException {
        private static final long serialVersionUID = 1L;
        private ReauthenticationRequiredException(String message) {
            super(message);
        }
    }

    private static final class ServiceUnavailableException extends RuntimeException {
        private static final long serialVersionUID = 1L;
        private ServiceUnavailableException(String message) {
            super(message);
        }

        private ServiceUnavailableException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    private static final class NotFoundException extends RuntimeException {
        private static final long serialVersionUID = 1L;
        private NotFoundException(String message) {
            super(message);
        }
    }

    private static final class SetOfMethods {
        private static final java.util.Set<String> SUPPORTED =
                java.util.Set.of("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE");

        private SetOfMethods() { }
    }

    private static final class SecureTokenComparison {
        private static boolean matches(String expected, String supplied) {
            return com.xfestudio.xfeservermanager.infra.security.SecureTokens.constantTimeEquals(
                    com.xfestudio.xfeservermanager.infra.security.SecureTokens.sha256(expected),
                    com.xfestudio.xfeservermanager.infra.security.SecureTokens.sha256(supplied));
        }

        private SecureTokenComparison() { }
    }
}
