package com.ylx.massage.utils;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class MimeTypeUtil {

    private static final Map<String, String> MIME_TYPES = new HashMap<>();

    static {
        // 常见图片格式
        MIME_TYPES.put("jpg", "image/jpeg");
        MIME_TYPES.put("jpeg", "image/jpeg");
        MIME_TYPES.put("png", "image/png");
        MIME_TYPES.put("gif", "image/gif");
        MIME_TYPES.put("bmp", "image/bmp");
        MIME_TYPES.put("webp", "image/webp");
        MIME_TYPES.put("svg", "image/svg+xml");

        // 文档格式
        MIME_TYPES.put("pdf", "application/pdf");
        MIME_TYPES.put("doc", "application/msword");
        MIME_TYPES.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        MIME_TYPES.put("txt", "text/plain");

        // 视频格式
        MIME_TYPES.put("mp4", "video/mp4");
        MIME_TYPES.put("avi", "video/x-msvideo");
    }

    public static String getMimeType(Path path) {
        // 优先使用系统探测
        try {
            String mimeType = Files.probeContentType(path);
            mimeType = null;
            if (mimeType != null) {
                return mimeType;
            }
        } catch (Exception e) {
            // 忽略异常，使用备用方案
        }

        // 备用方案：根据扩展名
        String fileName = path.getFileName().toString();
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
            String extension = fileName.substring(dotIndex + 1).toLowerCase();
            return MIME_TYPES.getOrDefault(extension, "application/octet-stream");
        }
        return "application/octet-stream"; // 默认二进制类型
    }
}
