package click.kamil.springstatemachineexporter.analysis.enricher.routing;

import click.kamil.springstatemachineexporter.ast.common.AstUtils;
import click.kamil.springstatemachineexporter.ast.common.CodebaseContext;
import org.eclipse.jdt.core.dom.Annotation;
import org.eclipse.jdt.core.dom.TypeDeclaration;

/**
 * Maps {@code @EnableStateMachine(name=…)} bean names to configuration class FQNs.
 */
final class EnableStateMachineBeanRouting {

    private EnableStateMachineBeanRouting() {
    }

    static Boolean matchesNamedBean(String beanName, String currentMachineConfigFqn, CodebaseContext context) {
        String normalized = stripQuotes(beanName);
        if (normalized == null || normalized.isEmpty() || context == null || currentMachineConfigFqn == null) {
            return null;
        }
        String matchingConfig = findConfigFqnByBeanName(normalized, context);
        if (matchingConfig == null) {
            return null;
        }
        return currentMachineConfigFqn.equals(matchingConfig);
    }

    static String findConfigFqnByBeanName(String beanName, CodebaseContext context) {
        for (TypeDeclaration configType : context.findEntryPointClasses(java.util.List.of("EnableStateMachine"))) {
            String configFqn = context.getFqn(configType);
            String configuredName = extractEnableStateMachineName(configType);
            if (configuredName == null || configuredName.isEmpty()) {
                configuredName = defaultBeanName(configType.getName().getIdentifier());
            }
            if (beanName.equals(configuredName)) {
                return configFqn;
            }
        }
        return null;
    }

    static String extractEnableStateMachineName(TypeDeclaration configType) {
        for (Object modifierObj : configType.modifiers()) {
            if (!(modifierObj instanceof Annotation annotation)) {
                continue;
            }
            if (!annotation.getTypeName().toString().endsWith("EnableStateMachine")) {
                continue;
            }
            String name = AstUtils.extractAnnotationMember(annotation, "name");
            if (name != null && !name.isBlank()) {
                return stripQuotes(name);
            }
            String value = AstUtils.extractAnnotationMember(annotation, "value");
            if (value != null && !value.isBlank()) {
                return stripQuotes(value);
            }
        }
        return null;
    }

    static String defaultBeanNameFromFqn(String fqn) {
        if (fqn == null || !fqn.contains(".")) {
            return fqn;
        }
        String simple = fqn.substring(fqn.lastIndexOf('.') + 1);
        return defaultBeanName(simple);
    }

    private static String defaultBeanName(String simpleClassName) {
        if (simpleClassName == null || simpleClassName.isEmpty()) {
            return simpleClassName;
        }
        return Character.toLowerCase(simpleClassName.charAt(0)) + simpleClassName.substring(1);
    }

    private static String stripQuotes(String raw) {
        if (raw == null || raw.isBlank()) {
            return null;
        }
        String trimmed = raw.trim();
        if (trimmed.length() >= 2 && trimmed.startsWith("\"") && trimmed.endsWith("\"")) {
            return trimmed.substring(1, trimmed.length() - 1);
        }
        return trimmed;
    }
}
