package com.njcn.gather.tool.parsepqdif.component;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/**
 * PQDIF 原始文件本地存储服务。
 */
@Component
public class PqdifFileStorageService {

    private static final String DEFAULT_STORAGE_DIR = "data/parse-pqdif";
    private static final String PQDIF_STORAGE_DIR = "pqdif-files";

    @Value("${files.path:}")
    private String filesPath;

    public String save(MultipartFile pqdifFile) {
        if (pqdifFile == null || pqdifFile.isEmpty()) {
            throw new IllegalArgumentException("PQDIF文件不能为空");
        }
        try {
            Path storageDir = resolveStorageDir();
            Files.createDirectories(storageDir);
            if (!Files.isDirectory(storageDir)) {
                throw new IllegalStateException("PQDIF文件存储路径不是目录：" + storageDir);
            }
            String fileName = UUID.randomUUID().toString().replace("-", "") + "_" + sanitizeFileName(pqdifFile.getOriginalFilename());
            Path target = storageDir.resolve(fileName).normalize();
            if (!target.startsWith(storageDir)) {
                throw new IllegalArgumentException("PQDIF文件名不合法");
            }
            try (InputStream inputStream = pqdifFile.getInputStream()) {
                Files.copy(inputStream, target, StandardCopyOption.REPLACE_EXISTING);
            }
            return target.toString();
        } catch (Exception ex) {
            throw new IllegalArgumentException("保存PQDIF文件失败：" + ex.getMessage(), ex);
        }
    }

    private Path resolveStorageDir() {
        String configuredPath = trimToNull(filesPath);
        Path path = configuredPath == null ? Paths.get(DEFAULT_STORAGE_DIR) : Paths.get(configuredPath, PQDIF_STORAGE_DIR);
        return path.toAbsolutePath().normalize();
    }

    private String sanitizeFileName(String originalFilename) {
        String fileName = trimToNull(originalFilename);
        if (fileName == null) {
            return "unnamed.pqd";
        }
        String normalizedName = Paths.get(fileName).getFileName().toString();
        return normalizedName.replaceAll("[\\\\/:*?\"<>|]", "_");
    }

    private String trimToNull(String value) {
        if (value == null) {
            return null;
        }
        String text = value.trim();
        return text.isEmpty() ? null : text;
    }
}
