package com.emoon.tongue;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;

import java.util.Arrays;
import java.util.Locale;

/**
 * @author destiny
 * @description:
 * @date 2025/12/9 19:34
 */
@SpringBootApplication(scanBasePackages = {
    "com.emoon.common",
    "com.emoon.tongue",
})
@ConfigurationPropertiesScan(basePackages = {
    "com.emoon.tongue.config",
})
public class TongueApplication {

    public static void main(String[] args) {
        Class<?> appClass = isRelayOnlyStartup(args) ? TongueRelayOnlyApplication.class : TongueApplication.class;
        SpringApplication.run(appClass, args);
        System.out.println("启动成功");
    }

    private static boolean isRelayOnlyStartup(String[] args) {
        if (hasTruthyValue(System.getProperty("tongue.relay-only"))) {
            return true;
        }
        if (hasTruthyValue(System.getenv("TONGUE_RELAY_ONLY"))) {
            return true;
        }
        if (args != null) {
            for (String arg : args) {
                if (arg == null) {
                    continue;
                }
                if (arg.startsWith("--tongue.relay-only=") && hasTruthyValue(arg.substring("--tongue.relay-only=".length()))) {
                    return true;
                }
                if (arg.startsWith("--spring.profiles.active=") && containsRelayProfile(arg.substring("--spring.profiles.active=".length()))) {
                    return true;
                }
            }
        }
        return containsRelayProfile(System.getProperty("spring.profiles.active"))
            || containsRelayProfile(System.getenv("SPRING_PROFILES_ACTIVE"));
    }

    private static boolean hasTruthyValue(String value) {
        if (value == null) {
            return false;
        }
        String normalized = value.trim().toLowerCase(Locale.ROOT);
        return "true".equals(normalized) || "1".equals(normalized) || "yes".equals(normalized) || "on".equals(normalized);
    }

    private static boolean containsRelayProfile(String profiles) {
        if (profiles == null || profiles.trim().isEmpty()) {
            return false;
        }
        return Arrays.stream(profiles.split(","))
            .map(profile -> profile == null ? "" : profile.trim().toLowerCase(Locale.ROOT))
            .anyMatch("relay"::equals);
    }

}
