package com.easyagents.skill.util;

import com.easyagents.skill.model.SkillResourceKind;

import java.util.Locale;
import java.util.Set;

/**
 * 通用 Skill 资源识别工具。
 */
public final class SkillResources {

    private static final Set<String> TEXT_EXTENSIONS = Set.of(
            ".md", ".markdown", ".txt", ".json", ".yaml", ".yml", ".xml", ".csv", ".tsv",
            ".htm", ".html", ".svg", ".css", ".scss", ".less", ".properties", ".toml", ".ini",
            ".conf", ".config", ".env", ".sql", ".graphql", ".gql", ".proto", ".java", ".kt", ".kts",
            ".py", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".sh", ".bash", ".zsh",
            ".rb", ".go", ".rs", ".c", ".h", ".cpp", ".hpp", ".gradle", ".groovy", ".vue", ".svelte"
    );

    private static final Set<String> TEXT_FILE_NAMES = Set.of(
            "dockerfile", "makefile", "gradlew", ".gitignore", ".gitattributes", ".editorconfig"
    );

    private SkillResources() {
    }

    /**
     * 根据顶层目录识别资源语义类型。
     *
     * @param path Skill 根目录相对路径
     * @return 资源语义类型
     */
    public static SkillResourceKind classify(String path) {
        String topDirectory = SkillPaths.firstSegment(path);
        return switch (topDirectory) {
            case SkillPaths.REFERENCES_DIR -> SkillResourceKind.REFERENCE;
            case SkillPaths.SCRIPTS_DIR -> SkillResourceKind.SCRIPT;
            case SkillPaths.ASSETS_DIR -> SkillResourceKind.ASSET;
            case SkillPaths.EXAMPLES_DIR -> SkillResourceKind.EXAMPLE;
            default -> SkillResourceKind.OTHER;
        };
    }

    /**
     * 判断资源是否应按严格 UTF-8 文本处理。
     *
     * @param path 资源路径
     * @param mediaType 媒体类型
     * @return 文本资源时为 true
     */
    public static boolean isText(String path, String mediaType) {
        String normalizedMediaType = mediaType == null ? "" : mediaType.toLowerCase(Locale.ROOT);
        if (normalizedMediaType.startsWith("text/")
                || normalizedMediaType.contains("json") || normalizedMediaType.contains("yaml")
                || normalizedMediaType.contains("xml") || normalizedMediaType.contains("javascript")
                || normalizedMediaType.contains("typescript") || normalizedMediaType.contains("toml")
                || normalizedMediaType.contains("sql")) {
            return true;
        }
        String lowerPath = path.toLowerCase(Locale.ROOT);
        String fileName = SkillPaths.fileName(lowerPath);
        return TEXT_FILE_NAMES.contains(fileName)
                || TEXT_EXTENSIONS.stream().anyMatch(lowerPath::endsWith);
    }

}
