package click.kamil.springstatemachineexporter.analysis.enricher;

import java.util.List;
import java.util.Locale;

/**
 * Extracts normalized domain keys from state machine configuration class names
 * (e.g. {@code StandardOrderStateMachineConfiguration} → {@code ORDER}).
 */
public final class MachineDomainKeys {

    private MachineDomainKeys() {
    }

    public static String extractMachineDomainKey(String machineName) {
        String simple = machineName.substring(machineName.lastIndexOf('.') + 1);
        String upper = simple.toUpperCase(Locale.ROOT);
        for (String marker : List.of("STATEMACHINECONFIGURATION", "STATEMACHINE", "CONFIGURATION", "CONFIG")) {
            int idx = upper.indexOf(marker);
            if (idx > 0) {
                return normalizeDomainKey(upper.substring(0, idx));
            }
        }
        int stateIdx = upper.indexOf("STATE");
        if (stateIdx > 0) {
            return normalizeDomainKey(upper.substring(0, stateIdx));
        }
        return normalizeDomainKey(upper);
    }

    private static String normalizeDomainKey(String domain) {
        if (domain == null || domain.isEmpty()) {
            return domain;
        }
        String upper = domain.toUpperCase(Locale.ROOT);
        if (upper.startsWith("STANDARD") && upper.length() > "STANDARD".length()) {
            return upper.substring("STANDARD".length());
        }
        return upper;
    }
}
