package com.example.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.repository.ImageToVideoTaskRepository;
import com.example.demo.repository.TaskQueueRepository;
import com.example.demo.repository.TextToVideoTaskRepository;
import com.example.demo.service.TaskCleanupService;

/**
 * 清理控制器
 * 用于清理失败的任务和相关数据
 */
@RestController
@RequestMapping("/api/cleanup")
public class CleanupController {

    @Autowired
    private TaskQueueRepository taskQueueRepository;

    @Autowired
    private ImageToVideoTaskRepository imageToVideoTaskRepository;

    @Autowired
    private TextToVideoTaskRepository textToVideoTaskRepository;

    @Autowired
    private TaskCleanupService taskCleanupService;

    /**
     * 清理所有失败的任务
     */
    @PostMapping("/failed-tasks")
    public ResponseEntity<Map<String, Object>> cleanupFailedTasks() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 统计清理前的数量
            long failedQueueCount = taskQueueRepository.findByStatus(com.example.demo.model.TaskQueue.QueueStatus.FAILED).size();
            long failedImageCount = imageToVideoTaskRepository.findByStatus(com.example.demo.model.ImageToVideoTask.TaskStatus.FAILED).size();
            long failedTextCount = textToVideoTaskRepository.findByStatus(com.example.demo.model.TextToVideoTask.TaskStatus.FAILED).size();
            
            // 删除失败的任务队列记录
            taskQueueRepository.deleteByStatus(com.example.demo.model.TaskQueue.QueueStatus.FAILED);
            
            // 删除失败的图生视频任务
            imageToVideoTaskRepository.deleteByStatus(com.example.demo.model.ImageToVideoTask.TaskStatus.FAILED.toString());
            
            // 删除失败的文生视频任务
            textToVideoTaskRepository.deleteByStatus(com.example.demo.model.TextToVideoTask.TaskStatus.FAILED.toString());
            
            // 注意：积分冻结记录的清理需要根据实际业务需求实现
            // 这里暂时注释掉，避免引用不存在的Repository
            // pointsFreezeRecordRepository.deleteByStatusIn(...)
            
            response.put("success", true);
            response.put("message", "失败任务清理完成");
            response.put("cleanedQueueTasks", failedQueueCount);
            response.put("cleanedImageTasks", failedImageCount);
            response.put("cleanedTextTasks", failedTextCount);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "清理失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 执行完整的任务清理
     * 将成功任务导出到归档表，删除失败任务
     */
    @PostMapping("/full-cleanup")
    public ResponseEntity<Map<String, Object>> performFullCleanup() {
        Map<String, Object> result = taskCleanupService.performFullCleanup();
        return ResponseEntity.ok(result);
    }
    
    /**
     * 清理指定用户的任务
     */
    @PostMapping("/user-tasks/{username}")
    public ResponseEntity<Map<String, Object>> cleanupUserTasks(@PathVariable String username) {
        Map<String, Object> result = taskCleanupService.cleanupUserTasks(username);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取清理统计信息
     */
    @GetMapping("/cleanup-stats")
    public ResponseEntity<Map<String, Object>> getCleanupStats() {
        Map<String, Object> stats = taskCleanupService.getCleanupStats();
        return ResponseEntity.ok(stats);
    }
}
