package click.kamil.springstatemachineexporter.analysis.resolver;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.Path;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * Discovers related local modules by statically parsing Maven/Gradle build files (never executes build tools).
 */
@Slf4j
public class SiblingDependencyResolver {

    private final StaticBuildFileAnalyzer analyzer = new StaticBuildFileAnalyzer();

    public ProjectModuleGraph analyzeProject(Path inputDir) throws IOException {
        return analyzer.analyze(inputDir);
    }

    public Set<Path> resolveSiblings(Path projectDir) {
        try {
            ProjectModuleGraph graph = analyzer.analyze(projectDir);
            return resolveSiblings(graph, projectDir);
        } catch (IOException e) {
            log.warn("Error resolving sibling dependencies for {}", projectDir, e);
            return Set.of();
        }
    }

    public Set<Path> resolveSiblings(ProjectModuleGraph graph, Path inputDir) {
        Set<Path> scanPaths = graph.resolveScanPaths(inputDir);
        Set<Path> siblings = new LinkedHashSet<>();
        Path normalizedInput = inputDir.toAbsolutePath().normalize();
        for (Path path : scanPaths) {
            if (!path.equals(normalizedInput)) {
                siblings.add(path);
            }
        }
        return siblings;
    }
}
