package com.aicheck.analyzer;

import com.aicheck.config.AppConfig;
import com.aicheck.model.ApiEndpoint;
import com.aicheck.parser.EndpointParser;

import java.io.IOException;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 预扫描 Controller/Feign 目录，构建 endpointKey → ApiEndpoint 索引。
 */
public class EndpointIndexBuilder {
    private final EndpointParser endpointParser = new EndpointParser();

    /** 合并 Controller 与 Feign 扫描结果 */
    public Map<String, ApiEndpoint> buildIndex(Path repoRoot, AppConfig config) throws IOException {
        Map<String, ApiEndpoint> index = new LinkedHashMap<>();
        for (String dir : config.getControllerScanDirs()) {
            addEndpoints(index, endpointParser.scanControllerDirectory(repoRoot.resolve(dir), dir));
        }
        for (String dir : config.getFeignScanDirs()) {
            addEndpoints(index, endpointParser.scanFeignDirectory(repoRoot.resolve(dir), dir));
        }
        return index;
    }

    /** 按 endpointKey 去重写入索引 */
    private void addEndpoints(Map<String, ApiEndpoint> index, List<ApiEndpoint> endpoints) {
        for (ApiEndpoint endpoint : endpoints) {
            index.putIfAbsent(endpoint.endpointKey(), endpoint);
        }
    }
}
