package com.weather.modules.weather.filescan;

import cn.hutool.core.util.StrUtil;
import com.weather.common.constant.Constant;
import com.weather.modules.sys.service.SysParamsService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@AllArgsConstructor
public class FileScanStartupRunner {

    /**
     * 启动后延迟扫描时间（秒），给应用留出充分的初始化时间
     */
    private static final long STARTUP_DELAY_SECONDS = 30;

    private final SysParamsService sysParamsService;
    private final FileWatchServiceManager fileWatchServiceManager;

    @Async
    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        log.info("应用已启动，{} 秒后开始文件扫描目录初始化...", STARTUP_DELAY_SECONDS);
        try {
            TimeUnit.SECONDS.sleep(STARTUP_DELAY_SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.warn("文件扫描延迟等待被中断，直接开始初始化");
        }

        String rootPath = sysParamsService.getValue(Constant.FILE_SCAN_ROOT_PATH);
        if (StrUtil.isBlank(rootPath) || "0".equals(rootPath)) {
            log.warn("FILE_SCAN_ROOT_PATH 未配置，跳过文件扫描目录初始化");
            return;
        }

        fileWatchServiceManager.ensureDirectoriesExist();
        fileWatchServiceManager.registerDeptDirectories();
        fileWatchServiceManager.scanAllDirectories();

        log.info("文件扫描目录初始化完成，根路径: {}", rootPath);
    }
}
