import logger from '@/lib/logger.js';
import { GenerationTask } from '@/lib/database/models/GenerationTask.js';
import { GenerationResult } from '@/lib/database/models/GenerationResult.js';

/**
 * NeDB 数据清理服务
 * 负责定期清理过期的任务和结果数据
 */
export class NeDBCleanupService {
    private static instance: NeDBCleanupService;
    private cleanupInterval: NodeJS.Timeout | null = null;
    private readonly CLEANUP_INTERVAL = 60 * 60 * 1000; // 1小时清理一次
    private isRunning = false;

    private constructor() {}

    static getInstance(): NeDBCleanupService {
        if (!NeDBCleanupService.instance) {
            NeDBCleanupService.instance = new NeDBCleanupService();
        }
        return NeDBCleanupService.instance;
    }

    /**
     * 启动清理服务
     */
    async start(): Promise<void> {
        if (this.isRunning) {
            logger.warn('NeDB cleanup service is already running');
            return;
        }

        this.isRunning = true;
        logger.info('Starting NeDB cleanup service...');

        // 立即执行一次清理
        await this.performCleanup();

        // 设置定期清理
        this.cleanupInterval = setInterval(async () => {
            await this.performCleanup();
        }, this.CLEANUP_INTERVAL);

        logger.success('NeDB cleanup service started successfully');
    }

    /**
     * 停止清理服务
     */
    stop(): void {
        if (!this.isRunning) {
            logger.warn('NeDB cleanup service is not running');
            return;
        }

        if (this.cleanupInterval) {
            clearInterval(this.cleanupInterval);
            this.cleanupInterval = null;
        }

        this.isRunning = false;
        logger.info('NeDB cleanup service stopped');
    }

    /**
     * 执行清理操作
     */
    private async performCleanup(): Promise<void> {
        try {
            logger.info('Starting NeDB data cleanup...');
            const startTime = Date.now();

            // 清理过期的结果数据
            const expiredResultsCount = await this.cleanupExpiredResults();

            // 清理过期的任务数据
            const expiredTasksCount = await this.cleanupExpiredTasks();

            const duration = Date.now() - startTime;
            logger.success(
                `NeDB cleanup completed in ${duration}ms. ` +
                `Cleaned ${expiredResultsCount} expired results and ${expiredTasksCount} expired tasks`
            );
        } catch (error) {
            logger.error('Failed to perform NeDB cleanup:', error);
        }
    }

    /**
     * 清理过期的结果数据
     */
    private async cleanupExpiredResults(): Promise<number> {
        try {
            const deletedCount = await GenerationResult.cleanupExpiredResults();
            if (deletedCount > 0) {
                logger.info(`Cleaned up ${deletedCount} expired generation results`);
            }
            return deletedCount;
        } catch (error) {
            logger.error('Failed to cleanup expired results:', error);
            return 0;
        }
    }

    /**
     * 清理过期的任务数据
     * 清理超过 7 天的已完成任务
     */
    private async cleanupExpiredTasks(): Promise<number> {
        try {
            const sevenDaysAgo = Date.now() - (7 * 24 * 60 * 60 * 1000);
            
            // 删除超过 7 天的已完成任务
            const deletedCount = await GenerationTask.deleteMany({
                status: { $in: ['completed', 'failed', 'cancelled', 'processing_success'] },
                created_at: { $lt: sevenDaysAgo }
            });

            if (deletedCount > 0) {
                logger.info(`Cleaned up ${deletedCount} expired generation tasks`);
            }
            return deletedCount;
        } catch (error) {
            logger.error('Failed to cleanup expired tasks:', error);
            return 0;
        }
    }

    /**
     * 手动触发清理
     */
    async manualCleanup(): Promise<{ expiredResults: number; expiredTasks: number }> {
        logger.info('Manual NeDB cleanup triggered');
        
        const expiredResults = await this.cleanupExpiredResults();
        const expiredTasks = await this.cleanupExpiredTasks();
        
        return { expiredResults, expiredTasks };
    }

    /**
     * 获取清理服务状态
     */
    getStatus(): { isRunning: boolean; nextCleanup?: number } {
        const status: { isRunning: boolean; nextCleanup?: number } = {
            isRunning: this.isRunning
        };

        if (this.isRunning && this.cleanupInterval) {
            // 估算下次清理时间（不完全准确，但提供参考）
            status.nextCleanup = Date.now() + this.CLEANUP_INTERVAL;
        }

        return status;
    }
}

// 导出单例实例
export default NeDBCleanupService.getInstance();