package com.qqchen.deploy.backend.deploy.api;

import com.qqchen.deploy.backend.deploy.dto.FileUploadResultDTO;
import com.qqchen.deploy.backend.deploy.dto.RemoteFileInfoDTO;
import com.qqchen.deploy.backend.deploy.service.impl.ServerSSHFileService;
import com.qqchen.deploy.backend.framework.api.Response;
import com.qqchen.deploy.backend.framework.ssh.file.FileUploadTask;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * 服务器SSH文件管理API（业务层）
 * 
 * 提供文件浏览、上传、下载、删除等功能
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/server-ssh")
public class ServerSSHFileApiController {
    
    @Resource
    private ServerSSHFileService serverSSHFileService;
    
    /**
     * 浏览远程目录
     * 
     * @param serverId 服务器ID
     * @param path 目录路径（默认为用户主目录）
     * @return 文件列表
     */
    @GetMapping("/{serverId}/files/browse")
    public Response<List<RemoteFileInfoDTO>> browseDirectory(
        @PathVariable Long serverId,
        @RequestParam(value = "path", defaultValue = "~") String path
    ) {
        log.info("浏览目录: serverId={}, path={}", serverId, path);
        
        // 处理~符号（用户主目录）
        if ("~".equals(path)) {
            path = "/home";  // 可以根据实际情况调整默认路径
        }
        
        // Service层已经处理转换
        List<RemoteFileInfoDTO> dtos = serverSSHFileService.listDirectoryAsDTO(serverId, path);
        
        return Response.success(dtos);
    }
    
    /**
     * 创建目录
     * 
     * @param serverId 服务器ID
     * @param path 目录路径
     * @return 成功标志
     */
    @PostMapping("/{serverId}/files/mkdir")
    public Response<Void> createDirectory(
        @PathVariable Long serverId,
        @RequestParam("path") String path
    ) {
        log.info("创建目录: serverId={}, path={}", serverId, path);
        
        serverSSHFileService.createDirectory(serverId, path);
        
        return Response.success();
    }
    
    /**
     * 删除文件或目录
     * 
     * @param serverId 服务器ID
     * @param path 文件/目录路径
     * @param recursive 是否递归删除（目录时使用）
     * @return 成功标志
     */
    @DeleteMapping("/{serverId}/files/remove")
    public Response<Void> deleteFile(
        @PathVariable Long serverId,
        @RequestParam("path") String path,
        @RequestParam(value = "recursive", defaultValue = "false") Boolean recursive
    ) {
        log.info("删除文件: serverId={}, path={}, recursive={}", serverId, path, recursive);
        
        serverSSHFileService.deleteFile(serverId, path, recursive);
        
        return Response.success();
    }
    
    /**
     * 上传文件
     * 
     * @param serverId 服务器ID
     * @param file 文件
     * @param remotePath 远程路径（完整路径，包括文件名）
     * @param overwrite 是否覆盖已存在的文件
     * @return 上传结果
     */
    @PostMapping("/{serverId}/files/upload")
    public Response<FileUploadResultDTO> uploadFile(
        @PathVariable Long serverId,
        @RequestParam("file") MultipartFile file,
        @RequestParam("remotePath") String remotePath,
        @RequestParam(value = "overwrite", defaultValue = "false") Boolean overwrite
    ) {
        log.info("上传文件: serverId={}, fileName={}, remotePath={}, size={}, overwrite={}",
            serverId, file.getOriginalFilename(), remotePath, file.getSize(), overwrite);
        
        // Service层已经处理转换
        FileUploadResultDTO result = serverSSHFileService.uploadFileAsDTO(serverId, file, remotePath, overwrite);
        
        return Response.success(result);
    }
    
    /**
     * 重命名文件或目录
     * 
     * @param serverId 服务器ID
     * @param oldPath 原路径
     * @param newPath 新路径
     * @return 成功标志
     */
    @PutMapping("/{serverId}/files/rename")
    public Response<Void> renameFile(
        @PathVariable Long serverId,
        @RequestParam("oldPath") String oldPath,
        @RequestParam("newPath") String newPath
    ) {
        log.info("重命名文件: serverId={}, oldPath={}, newPath={}", serverId, oldPath, newPath);
        
        serverSSHFileService.renameFile(serverId, oldPath, newPath);
        
        return Response.success();
    }
    
    // ========== 异步上传相关接口 ==========
    
    /**
     * 异步上传文件（立即返回任务ID）
     * 
     * @param serverId 服务器ID
     * @param file 文件
     * @param remotePath 远程路径
     * @param overwrite 是否覆盖
     * @return 任务ID和提示信息
     */
    @PostMapping("/{serverId}/files/upload-async")
    public Response<Map<String, String>> uploadFileAsync(
        @PathVariable Long serverId,
        @RequestParam("file") MultipartFile file,
        @RequestParam("remotePath") String remotePath,
        @RequestParam(value = "overwrite", defaultValue = "false") Boolean overwrite
    ) {
        log.info("提交异步上传任务: serverId={}, fileName={}, remotePath={}, size={}", 
            serverId, file.getOriginalFilename(), remotePath, file.getSize());
        
        String taskId = serverSSHFileService.uploadFileAsync(serverId, file, remotePath, overwrite);
        
        return Response.success(Map.of(
            "taskId", taskId,
            "message", "上传任务已提交，请通过WebSocket订阅进度：/topic/upload/" + taskId
        ));
    }
    
    /**
     * 查询上传任务状态
     * 
     * @param serverId 服务器ID
     * @param taskId 任务ID
     * @return 任务状态
     */
    @GetMapping("/{serverId}/files/upload-task/{taskId}")
    public Response<FileUploadTask> getUploadTaskStatus(
        @PathVariable Long serverId,
        @PathVariable String taskId
    ) {
        FileUploadTask task = serverSSHFileService.getUploadTaskStatus(serverId, taskId);
        return Response.success(task);
    }
    
    /**
     * 取消上传任务
     * 
     * @param serverId 服务器ID
     * @param taskId 任务ID
     * @return 是否取消成功（true=取消成功，false=无法取消）
     */
    @DeleteMapping("/{serverId}/files/upload-task/{taskId}")
    public Response<Boolean> cancelUploadTask(
        @PathVariable Long serverId,
        @PathVariable String taskId
    ) {
        boolean cancelled = serverSSHFileService.cancelUploadTask(serverId, taskId);
        return Response.success(cancelled);
    }
    
    /**
     * 获取上传任务统计
     * 
     * @param serverId 服务器ID
     * @return 任务统计信息
     */
    @GetMapping("/{serverId}/files/upload-statistics")
    public Response<Map<String, Integer>> getUploadStatistics(
        @PathVariable Long serverId
    ) {
        return Response.success(serverSSHFileService.getUploadTaskStatistics());
    }
}
