package click.kamil.springstatemachineexporter.analysis.index;

import click.kamil.springstatemachineexporter.ast.common.CodebaseContext;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public final class IndexedFieldConstantsIndexBuilder {

    public IndexedFieldConstantsIndex build(CodebaseContext context, AccessorIndex accessorIndex) {
        if (context == null || accessorIndex == null) {
            return IndexedFieldConstantsIndex.empty();
        }

        Map<String, Map<String, List<String>>> entries = new HashMap<>();
        int entryCount = 0;

        for (Map.Entry<String, Map<String, AccessorSummary>> ownerEntry : accessorIndex.asMap().entrySet()) {
            String ownerFqn = ownerEntry.getKey();
            for (AccessorSummary accessor : ownerEntry.getValue().values()) {
                if (!accessor.isGetter() || accessor.fieldName() == null) {
                    continue;
                }
                List<String> constants = ScanTimeAccessorConstants.resolve(
                        context, accessorIndex, ownerFqn, accessor.methodName());
                if (constants.isEmpty()) {
                    continue;
                }
                entries.computeIfAbsent(ownerFqn, ignored -> new HashMap<>())
                        .put(accessor.methodName(), List.copyOf(constants));
                entryCount++;
            }
        }

        log.info("Built indexed field-constants index: {} entries across {} types", entryCount, entries.size());
        return new IndexedFieldConstantsIndex(entries, entryCount);
    }
}
