package com.codechecker.api.scanner;

import com.codechecker.git.GitChangeScanner;

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

/**
 * 扫描 API 相关 Java 文件变更（Controller / Feign），与类变更扫描解耦。
 */
public class ApiFileChangeScanner {
    private final GitChangeScanner gitScanner;

    public ApiFileChangeScanner(GitChangeScanner gitScanner) {
        this.gitScanner = gitScanner;
    }

    /** 返回两次提交间变更的 .java 相对路径（位于 scanDirs 下） */
    public List<String> scanChangedFiles(Path repoRoot, List<String> scanDirs,
                                         String oldSha, String newSha) throws IOException {
        Set<String> changed = new LinkedHashSet<>();
        List<String> diffLines = gitScanner.diffNameOnly(oldSha, newSha);
        for (String line : diffLines) {
            String path = normalize(line);
            if (!path.endsWith(".java")) {
                continue;
            }
            if (isUnderScanDirs(path, scanDirs)) {
                changed.add(path);
            }
        }
        return new ArrayList<>(changed);
    }

    private boolean isUnderScanDirs(String relativePath, List<String> scanDirs) {
        String normalized = relativePath.replace('\\', '/');
        for (String dir : scanDirs) {
            String prefix = dir.replace('\\', '/');
            if (!prefix.endsWith("/")) {
                prefix = prefix + "/";
            }
            if (normalized.startsWith(prefix)) {
                return true;
            }
        }
        return false;
    }

    private String normalize(String path) {
        return path.replace('\\', '/').trim();
    }
}
