package com.infoepoch.pms.agent.platform.agent.adapter.out.tool.support;

import org.springframework.util.StringUtils;

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

/**
 * 聊天机器人工作区根目录解析器。
 */
public final class ChatbotWorkspaceRootResolver {

    private ChatbotWorkspaceRootResolver() {
    }

    /**
     * 解析工作区根目录。
     *
     * @param configuredWorkspaceRoot 配置中的目录
     * @param currentPath             当前工作目录
     * @return 归一化后的工作区目录
     */
    public static Path resolve(String configuredWorkspaceRoot, Path currentPath) {
        Path projectRoot = resolveProjectRoot(currentPath.toAbsolutePath().normalize());
        if (StringUtils.hasText(configuredWorkspaceRoot)) {
            Path configuredPath = Paths.get(configuredWorkspaceRoot.trim());
            if (configuredPath.isAbsolute()) {
                return configuredPath.normalize();
            }
            return projectRoot.resolve(configuredPath).normalize();
        }
        return projectRoot;
    }

    private static Path resolveProjectRoot(Path currentPath) {
        String currentName = currentPath.getFileName() != null ? currentPath.getFileName().toString() : "";
        if ("agent-lab-backend".equals(currentName) || "agent-lab-fronted".equals(currentName)) {
            return currentPath.getParent() != null ? currentPath.getParent() : currentPath;
        }
        return currentPath;
    }
}
