package com.aicheck;

import com.aicheck.analyzer.ClassChangeAnalyzer;
import com.aicheck.analyzer.EndpointIndexBuilder;
import com.aicheck.config.AppConfig;
import com.aicheck.git.GitChangeScanner;
import com.aicheck.model.ApiEndpoint;
import com.aicheck.model.ClassChangeReport;
import com.aicheck.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 = "class-checker", mixinStandardHelpOptions = true,
        description = "检测 Vo/Dto/Entity/Model 类变更并发送企业微信通知")
public class ClassCheckMain 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 ClassCheckMain()).execute(args);
        System.exit(exitCode);
    }

    /** 主流程：索引接口 → 分析变更 → 通知 */
    @Override
    public Integer call() throws Exception {
        AppConfig appConfig = AppConfig.load(config.toAbsolutePath());
        if (!appConfig.isEnabled()) {
            System.out.println("类变更检测已关闭（class_check.enabled=false）");
            return 0;
        }

        GitChangeScanner gitScanner = new GitChangeScanner(repoRoot.toAbsolutePath());
        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()) {
            if (appConfig.isOnlyOnChange()) {
                System.out.println("无类变更，静默退出");
            }
            return 0;
        }

        WeComNotifier notifier = new WeComNotifier();
        if (appConfig.isWecomEnabled()) {
            notifier.sendAll(appConfig.getWecomWebhookUrl(), reports, modifier, modifyTime);
        } else {
            notifier.logAll(reports, modifier, modifyTime);
        }
        return 0;
    }
}
