package com.lingyue.parse.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 图片访问控制器
 * 
 * @author lingyue
 * @since 2026-01-21
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/files")
@Tag(name = "文件访问", description = "图片和文件访问接口")
public class ImageController {
    
    @Value("${file.storage.base-path:/data/lingyue}")
    private String basePath;
    
    /**
     * 获取文档中的图片
     */
    @GetMapping("/images/{documentId}/{imageName}")
    @Operation(summary = "获取文档图片", description = "根据文档ID和图片名称获取图片")
    public ResponseEntity<Resource> getImage(
            @Parameter(description = "文档ID", required = true)
            @PathVariable String documentId,
            @Parameter(description = "图片文件名", required = true)
            @PathVariable String imageName) {
        
        try {
            // 安全检查：防止路径遍历攻击
            if (documentId.contains("..") || imageName.contains("..")) {
                log.warn("非法的路径访问尝试: documentId={}, imageName={}", documentId, imageName);
                return ResponseEntity.badRequest().build();
            }
            
            Path imagePath = Paths.get(basePath, "images", documentId, imageName);
            File imageFile = imagePath.toFile();
            
            if (!imageFile.exists()) {
                log.warn("图片不存在: {}", imagePath);
                return ResponseEntity.notFound().build();
            }
            
            // 检测内容类型
            String contentType = Files.probeContentType(imagePath);
            if (contentType == null) {
                // 根据扩展名推断
                String ext = imageName.substring(imageName.lastIndexOf('.') + 1).toLowerCase();
                switch (ext) {
                    case "png":
                        contentType = "image/png";
                        break;
                    case "jpg":
                    case "jpeg":
                        contentType = "image/jpeg";
                        break;
                    case "gif":
                        contentType = "image/gif";
                        break;
                    case "bmp":
                        contentType = "image/bmp";
                        break;
                    case "webp":
                        contentType = "image/webp";
                        break;
                    case "svg":
                        contentType = "image/svg+xml";
                        break;
                    case "emf":
                        contentType = "image/x-emf";
                        break;
                    case "wmf":
                        contentType = "image/x-wmf";
                        break;
                    default:
                        contentType = "application/octet-stream";
                }
            }
            
            Resource resource = new FileSystemResource(imageFile);
            
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CACHE_CONTROL, "max-age=86400") // 缓存1天
                    .body(resource);
            
        } catch (Exception e) {
            log.error("获取图片失败: documentId={}, imageName={}", documentId, imageName, e);
            return ResponseEntity.internalServerError().build();
        }
    }
}
