package com.cameleer.server.app.metrics;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;

/**
 * Resolves a stable identifier for this server process, used as the
 * {@code server_instance_id} on every server_metrics sample. The value is
 * fixed at boot, so counters restart cleanly whenever the id rotates.
 *
 * <p>Precedence:
 * <ol>
 *   <li>{@code cameleer.server.instance-id} property / {@code CAMELEER_SERVER_INSTANCE_ID} env
 *   <li>{@code HOSTNAME} env (populated by Docker/Kubernetes)
 *   <li>{@link InetAddress#getLocalHost()} hostname
 *   <li>Random UUID (fallback — only hit when DNS and env are both silent)
 * </ol>
 */
@Configuration
public class ServerInstanceIdConfig {

    private static final Logger log = LoggerFactory.getLogger(ServerInstanceIdConfig.class);

    @Bean("serverInstanceId")
    public String serverInstanceId(
            @Value("${cameleer.server.instance-id:}") String configuredId) {
        if (!isBlank(configuredId)) {
            log.info("Server instance id resolved from configuration: {}", configuredId);
            return configuredId;
        }

        String hostnameEnv = System.getenv("HOSTNAME");
        if (!isBlank(hostnameEnv)) {
            log.info("Server instance id resolved from HOSTNAME env: {}", hostnameEnv);
            return hostnameEnv;
        }

        try {
            String localHost = InetAddress.getLocalHost().getHostName();
            if (!isBlank(localHost)) {
                log.info("Server instance id resolved from localhost lookup: {}", localHost);
                return localHost;
            }
        } catch (UnknownHostException e) {
            log.debug("InetAddress.getLocalHost() failed, falling back to UUID: {}", e.getMessage());
        }

        String fallback = UUID.randomUUID().toString();
        log.warn("Server instance id could not be resolved; using random UUID {}", fallback);
        return fallback;
    }

    private static boolean isBlank(String s) {
        return s == null || s.isBlank();
    }
}
