package com.ycwl.basic.puzzle.fill.datasource;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.ycwl.basic.puzzle.fill.enums.DataSourceType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 静态值数据源策略
 * 支持直接返回配置值或指向本地文件的路径
 */
@Slf4j
@Component
public class StaticValueDataSourceStrategy implements DataSourceStrategy {

    @Override
    public String resolve(JsonNode sourceFilter, String sortStrategy, DataSourceContext context) {
        if (sourceFilter == null) {
            return null;
        }

        if (sourceFilter.hasNonNull("localPath")) {
            String localPath = sourceFilter.get("localPath").asText();
            return resolveLocalPath(localPath);
        }

        if (sourceFilter.hasNonNull("value")) {
            String value = sourceFilter.get("value").asText();
            log.debug("解析STATIC_VALUE成功, value={}", value);
            return value;
        }

        return null;
    }

    private String resolveLocalPath(String rawPath) {
        if (StrUtil.isBlank(rawPath)) {
            log.warn("localPath为空, 无法解析静态值数据源");
            return null;
        }

        try {
            Path path;
            if (StrUtil.startWithIgnoreCase(rawPath, "file:")) {
                path = Paths.get(new URI(rawPath));
            } else {
                path = Paths.get(rawPath);
            }

            if (!path.isAbsolute()) {
                path = path.toAbsolutePath();
            }

            if (!Files.exists(path) || !Files.isRegularFile(path)) {
                log.warn("localPath不存在或不是文件: {}", path);
                return null;
            }

            log.debug("解析STATIC_VALUE本地路径成功: {}", path);
            return path.toString();
        } catch (Exception e) {
            log.error("解析本地路径失败: {}", rawPath, e);
            return null;
        }
    }

    @Override
    public String getSupportedType() {
        return DataSourceType.STATIC_VALUE.getCode();
    }
}
