package com.codechecker;

import com.codechecker.analyzer.ClassChangeAnalyzer;
import com.codechecker.analyzer.EndpointIndexBuilder;
import com.codechecker.api.analyzer.ApiChangeAnalyzer;
import com.codechecker.api.model.EndpointChangeReport;
import com.codechecker.api.notify.ApiChangeNotifier;
import com.codechecker.config.AppConfig;
import com.codechecker.git.GitChangeScanner;
import com.codechecker.model.ApiEndpoint;
import com.codechecker.model.ClassChangeReport;
import com.codechecker.notify.WeComNotifier;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;

import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * CLI 入口：加载配置 → 扫描 git 变更 → 分析影响 → 输出/发送企微通知。
 */
@Command(name = "code-checker", mixinStandardHelpOptions = true,
        description = "检测类变更与 API 变更并发送企业微信通知")
public class CodeCheckMain implements Callable<Integer> {
    @Option(names = "--config", required = true, description = "配置文件路径")
    private Path config;

    @Option(names = "--repo-root", required = true, description = "仓库根目录")
    private Path repoRoot;

    @Option(names = "--old-sha", required = true, description = "旧提交 SHA")
    private String oldSha;

    @Option(names = "--new-sha", required = true, description = "新提交 SHA")
    private String newSha;

    @Option(names = "--modifier", required = true, description = "修改人")
    private String modifier;

    @Option(names = "--modify-time", required = true, description = "修改时间")
    private String modifyTime;

    /** 程序入口 */
    public static void main(String[] args) {
        int exitCode = new CommandLine(new CodeCheckMain()).execute(args);
        System.exit(exitCode);
    }

    /** 主流程：类变更与 API 变更独立检测、分条通知 */
    @Override
    public Integer call() throws Exception {
        AppConfig appConfig = AppConfig.load(config.toAbsolutePath());
        if (!appConfig.isMasterEnabled()) {
            System.out.println("变更检测已全部关闭（checker.enabled=false）");
            return 0;
        }

        GitChangeScanner gitScanner = new GitChangeScanner(repoRoot.toAbsolutePath());
        int totalSent = 0;

        if (appConfig.isClassCheckEnabled()) {
            totalSent += executeClassCheck(appConfig, gitScanner);
        } else {
            System.out.println("类变更检测已关闭（class_check.enabled=false）");
        }

        if (appConfig.isApiCheckEnabled()) {
            totalSent += executeApiCheck(appConfig, gitScanner);
        } else {
            System.out.println("API 变更检测已关闭（api_check.enabled=false）");
        }

        if (totalSent == 0 && appConfig.isOnlyOnChange()) {
            System.out.println("无变更，静默退出");
        }
        return 0;
    }

    private int executeClassCheck(AppConfig appConfig, GitChangeScanner gitScanner) throws Exception {
        System.out.println("=== 类变更检测 ===");
        EndpointIndexBuilder indexBuilder = new EndpointIndexBuilder();
        Map<String, ApiEndpoint> endpointIndex = indexBuilder.buildIndex(repoRoot.toAbsolutePath(), appConfig);
        System.out.println("已索引接口数量: " + endpointIndex.size());

        ClassChangeAnalyzer analyzer = new ClassChangeAnalyzer(gitScanner);
        List<ClassChangeReport> reports = analyzer.analyze(
                repoRoot.toAbsolutePath(), appConfig, oldSha, newSha, endpointIndex);
        System.out.println("检测到需通知的类变更数量: " + reports.size());
        if (reports.isEmpty()) {
            return 0;
        }
        WeComNotifier notifier = new WeComNotifier();
        if (appConfig.isWecomEnabled()) {
            return notifier.sendAll(appConfig.getWecomWebhookUrl(), reports, modifier, modifyTime);
        }
        notifier.logAll(reports, modifier, modifyTime);
        return reports.size();
    }

    private int executeApiCheck(AppConfig appConfig, GitChangeScanner gitScanner) throws Exception {
        System.out.println("=== API 变更检测 ===");
        ApiChangeAnalyzer analyzer = new ApiChangeAnalyzer(gitScanner);
        List<EndpointChangeReport> reports = analyzer.analyze(
                repoRoot.toAbsolutePath(), appConfig, oldSha, newSha);
        System.out.println("检测到需通知的 API 变更数量: " + reports.size());
        if (reports.isEmpty()) {
            return 0;
        }
        ApiChangeNotifier notifier = new ApiChangeNotifier();
        return notifier.sendAll(appConfig.getWecomWebhookUrl(), reports, modifier, modifyTime,
                appConfig.isWecomEnabled());
    }
}
