package com.lingyue.extract.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingyue.common.domain.AjaxResult;
import com.lingyue.extract.dto.request.CreateGenerationRequest;
import com.lingyue.extract.dto.request.GenerationProgressResponse;
import com.lingyue.extract.dto.request.UpdateVariableValueRequest;
import com.lingyue.extract.dto.response.GenerationResponse;
import com.lingyue.extract.entity.Generation;
import com.lingyue.extract.service.GenerationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 生成任务控制器
 * 
 * @author lingyue
 * @since 2026-01-24
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/generations")
@RequiredArgsConstructor
@Tag(name = "生成任务管理", description = "报告生成任务 CRUD 和执行接口")
public class GenerationController {
    
    private final GenerationService generationService;
    private final com.lingyue.extract.service.DocumentGenerationService documentGenerationService;
    
    /**
     * 获取当前用户ID
     * 开发阶段：如果未登录，使用默认测试用户
     */
    private String getCurrentUserId() {
        String userId = com.lingyue.common.util.SecurityUtils.getCurrentUserId();
        // 开发阶段：未登录时使用测试用户
        return userId != null ? userId : "00000000000000000000000000000002";
    }
    
    // ==================== 生成任务 CRUD ====================
    
    @PostMapping
    @Operation(summary = "创建生成任务", description = "创建新的报告生成任务")
    public AjaxResult<?> createGeneration(@Valid @RequestBody CreateGenerationRequest request) {
        try {
            String userId = getCurrentUserId();
            Generation generation = generationService.create(userId, request);
            return AjaxResult.success("创建成功", GenerationResponse.fromEntity(generation));
        } catch (Exception e) {
            log.error("创建生成任务失败", e);
            return AjaxResult.error("创建失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/{id}")
    @Operation(summary = "获取生成任务详情", description = "获取生成任务详细信息，包含变量值")
    public AjaxResult<?> getGeneration(
            @Parameter(description = "任务ID") @PathVariable String id) {
        GenerationResponse response = generationService.getDetail(id);
        if (response == null) {
            return AjaxResult.error("生成任务不存在");
        }
        return AjaxResult.success(response);
    }
    
    @GetMapping
    @Operation(summary = "获取生成任务列表", description = "分页获取当前用户的生成任务列表")
    public AjaxResult<?> listGenerations(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "20") int size) {
        String userId = getCurrentUserId();
        Page<GenerationResponse> result = generationService.listByUserId(userId, page, size);
        return AjaxResult.success(result);
    }
    
    @GetMapping("/recent")
    @Operation(summary = "获取最近的生成任务", description = "获取用户最近的生成任务")
    public AjaxResult<?> getRecentGenerations(
            @Parameter(description = "数量") @RequestParam(defaultValue = "10") int limit) {
        String userId = getCurrentUserId();
        List<GenerationResponse> result = generationService.getRecentByUserId(userId, limit);
        return AjaxResult.success(result);
    }
    
    @GetMapping("/template/{templateId}")
    @Operation(summary = "按模板获取生成任务", description = "获取指定模板的所有生成任务")
    public AjaxResult<?> listByTemplate(
            @Parameter(description = "模板ID") @PathVariable String templateId) {
        List<GenerationResponse> result = generationService.listByTemplateId(templateId);
        return AjaxResult.success(result);
    }
    
    @DeleteMapping("/{id}")
    @Operation(summary = "删除生成任务", description = "删除生成任务")
    public AjaxResult<?> deleteGeneration(
            @Parameter(description = "任务ID") @PathVariable String id) {
        try {
            boolean success = generationService.delete(id);
            if (!success) {
                return AjaxResult.error("生成任务不存在");
            }
            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            log.error("删除生成任务失败", e);
            return AjaxResult.error("删除失败: " + e.getMessage());
        }
    }
    
    // ==================== 执行相关 ====================
    
    @PostMapping("/{id}/execute")
    @Operation(summary = "执行提取", description = "开始执行变量提取")
    public AjaxResult<?> executeGeneration(
            @Parameter(description = "任务ID") @PathVariable String id) {
        try {
            Generation generation = generationService.execute(id);
            return AjaxResult.success("开始执行", GenerationResponse.fromEntity(generation));
        } catch (Exception e) {
            log.error("执行生成任务失败", e);
            return AjaxResult.error("执行失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/{id}/progress")
    @Operation(summary = "获取执行进度", description = "获取生成任务的执行进度")
    public AjaxResult<?> getProgress(
            @Parameter(description = "任务ID") @PathVariable String id) {
        GenerationProgressResponse progress = generationService.getProgress(id);
        if (progress == null) {
            return AjaxResult.error("生成任务不存在");
        }
        return AjaxResult.success(progress);
    }
    
    @PutMapping("/{id}/variables/{variableName}")
    @Operation(summary = "更新变量值", description = "手动修改生成任务中的变量值")
    public AjaxResult<?> updateVariableValue(
            @Parameter(description = "任务ID") @PathVariable String id,
            @Parameter(description = "变量名") @PathVariable String variableName,
            @Valid @RequestBody UpdateVariableValueRequest request) {
        try {
            Generation generation = generationService.updateVariableValue(id, variableName, request.getValue());
            return AjaxResult.success("更新成功", GenerationResponse.fromEntity(generation));
        } catch (Exception e) {
            log.error("更新变量值失败", e);
            return AjaxResult.error("更新失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/{id}/confirm")
    @Operation(summary = "确认并生成文档", description = "确认变量值并生成最终文档")
    public AjaxResult<?> confirmGeneration(
            @Parameter(description = "任务ID") @PathVariable String id) {
        try {
            Generation generation = generationService.confirm(id);
            return AjaxResult.success("确认成功，开始生成文档", GenerationResponse.fromEntity(generation));
        } catch (Exception e) {
            log.error("确认生成任务失败", e);
            return AjaxResult.error("确认失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/{id}/download")
    @Operation(summary = "下载生成的文档", description = "下载生成的报告文档")
    public org.springframework.http.ResponseEntity<org.springframework.core.io.Resource> downloadGeneration(
            @Parameter(description = "任务ID") @PathVariable String id) {
        try {
            org.springframework.core.io.Resource resource = documentGenerationService.getOutputFileResource(id);
            String fileName = documentGenerationService.getOutputFileName(id);
            
            return org.springframework.http.ResponseEntity.ok()
                    .header(org.springframework.http.HttpHeaders.CONTENT_DISPOSITION, 
                            "attachment; filename=\"" + java.net.URLEncoder.encode(fileName, "UTF-8") + "\"")
                    .header(org.springframework.http.HttpHeaders.CONTENT_TYPE, 
                            org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE)
                    .body(resource);
                    
        } catch (Exception e) {
            log.error("下载失败: id={}, error={}", id, e.getMessage());
            return org.springframework.http.ResponseEntity.notFound().build();
        }
    }
    
    @GetMapping("/{id}/download-info")
    @Operation(summary = "获取下载信息", description = "获取生成文档的下载信息")
    public AjaxResult<?> getDownloadInfo(
            @Parameter(description = "任务ID") @PathVariable String id) {
        Generation generation = generationService.getById(id);
        if (generation == null) {
            return AjaxResult.error("生成任务不存在");
        }
        
        if (!Generation.STATUS_COMPLETED.equals(generation.getStatus())) {
            return AjaxResult.error("文档尚未生成完成");
        }
        
        if (generation.getOutputFilePath() == null) {
            return AjaxResult.error("输出文件不存在");
        }
        
        return AjaxResult.success(java.util.Map.of(
                "fileName", documentGenerationService.getOutputFileName(id),
                "downloadUrl", "/api/v1/generations/" + id + "/download"
        ));
    }
}
