package com.njcn.gather.event.eventlist.service.impl;

import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 暂态事件波形文件路径解析器。
 */
final class EventWavePathResolver {

    private EventWavePathResolver() {
    }

    static WaveFilePath resolve(String storageRoot, String equipmentMac, String wavePath) {
        String rootText = requireText(storageRoot, "波形存储路径未配置");
        String mac = requireText(equipmentMac, "设备 MAC 为空");
        String normalizedWavePath = normalizeWavePath(wavePath);

        Path rootPath = Paths.get(rootText).normalize();
        Path rawWavePath = Paths.get(normalizedWavePath).normalize();
        Path eventBasePath;
        if (rawWavePath.isAbsolute()) {
            eventBasePath = rawWavePath;
        } else if (startsWithSegment(rawWavePath, mac)) {
            eventBasePath = rootPath.resolve(rawWavePath).normalize();
        } else {
            eventBasePath = rootPath.resolve(mac).resolve(rawWavePath).normalize();
        }

        if (!eventBasePath.startsWith(rootPath)) {
            throw new IllegalArgumentException("波形路径非法");
        }

        String fileName = eventBasePath.getFileName().toString();
        return new WaveFilePath(eventBasePath.resolveSibling(fileName + ".cfg"),
                eventBasePath.resolveSibling(fileName + ".dat"));
    }

    private static String normalizeWavePath(String value) {
        String wavePath = requireText(value, "事件 wave_path 为空").replace("\\", "/");
        String lowerWavePath = wavePath.toLowerCase();
        if (lowerWavePath.endsWith(".cfg") || lowerWavePath.endsWith(".dat")) {
            wavePath = wavePath.substring(0, wavePath.length() - 4);
        }
        if (wavePath.contains("..")) {
            throw new IllegalArgumentException("波形路径非法");
        }
        return wavePath;
    }

    private static boolean startsWithSegment(Path path, String segment) {
        return path.getNameCount() > 0 && path.getName(0).toString().equalsIgnoreCase(segment);
    }

    private static String requireText(String value, String message) {
        if (value == null || value.trim().isEmpty()) {
            throw new IllegalArgumentException(message);
        }
        return value.trim();
    }

    static class WaveFilePath {

        private final Path cfgPath;

        private final Path datPath;

        private WaveFilePath(Path cfgPath, Path datPath) {
            this.cfgPath = cfgPath;
            this.datPath = datPath;
        }

        Path getCfgPath() {
            return cfgPath;
        }

        Path getDatPath() {
            return datPath;
        }
    }
}
