package com.linkerbot.vibemake.service.cad.ai;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.linkerbot.vibemake.bean.ai.CadAiContracts.CadAiTool;
import com.linkerbot.vibemake.common.BusinessException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/** 版本化工具 Schema；动态引擎参数仍由浏览器的原生命令注册表校验。 */
@Component
public class CadAiTools {
    public static final String VERSION = "cad-agent-v1";
    private static final Logger log = LoggerFactory.getLogger(CadAiTools.class);
    private final List<CadAiTool> tools;
    private final Map<String, CadAiTool> byName;
    private final Map<String, Set<String>> skillFiles;
    private final String instructions;

    @Autowired
    public CadAiTools(ObjectMapper json) throws IOException {
        this(json, readKnowledgePolicy(json));
    }

    CadAiTools(ObjectMapper json, JsonNode knowledgePolicy) throws IOException {
        JsonNode bundle;
        try (InputStream input = new ClassPathResource("cad/ai/skills.json").getInputStream()) {
            bundle = json.readTree(input);
        }
        if (bundle == null || !bundle.path("formatVersion").isInt() || bundle.path("formatVersion").asInt() != 1
                || !bundle.path("revision").asText().matches("[a-f0-9]{64}")
                || !bundle.path("workflow").isTextual() || bundle.path("workflow").asText().isBlank()
                || !bundle.path("skills").isArray() || bundle.path("skills").isEmpty())
            throw new IOException("Invalid bundled CAD AI skills metadata");
        Map<String, Set<String>> filesBySkill = new LinkedHashMap<>();
        Set<String> allFiles = new TreeSet<>();
        StringBuilder catalog = new StringBuilder(bundle.path("workflow").asText())
                .append("\n\nAvailable makeCAD skills (read the relevant SKILL.md with skill_reference, then its needed references):\n");
        for (JsonNode skill : bundle.path("skills")) {
            String name = skill.path("name").asText();
            String description = skill.path("description").asText();
            JsonNode files = skill.path("files");
            if (!name.matches("makecad-[a-z][a-z0-9-]*") || !skill.path("description").isTextual() || description.isBlank()
                    || !files.isObject() || !files.path("SKILL.md").isTextual() || filesBySkill.containsKey(name))
                throw new IOException("Invalid bundled CAD AI skill entry: " + name);
            Set<String> paths = new TreeSet<>();
            Iterator<Map.Entry<String, JsonNode>> entries = files.fields();
            while (entries.hasNext()) {
                Map.Entry<String, JsonNode> entry = entries.next();
                String path = entry.getKey();
                if (!path.matches("(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]+\\.(?:md|py)")
                        || !entry.getValue().isTextual() || entry.getValue().asText().isBlank())
                    throw new IOException("Invalid bundled CAD AI skill document: " + name + "/" + path);
                paths.add(path);
            }
            filesBySkill.put(name, Set.copyOf(paths));
            allFiles.addAll(paths);
            catalog.append("- ").append(name).append(": ").append(description)
                    .append(" Files: ").append(String.join(", ", paths)).append('\n');
        }
        skillFiles = Map.copyOf(filesBySkill);
        instructions = catalog.toString();
        List<CadAiTool> definitions;
        try (InputStream input = new ClassPathResource("cad/ai/" + VERSION + ".json").getInputStream()) {
            definitions = new ArrayList<>(json.readValue(input, new TypeReference<List<CadAiTool>>() {}));
        }
        ObjectNode parameters = json.createObjectNode().put("type", "object").put("additionalProperties", false);
        parameters.putArray("required").add("skill");
        ObjectNode properties = parameters.putObject("properties");
        ArrayNode names = properties.putObject("skill").put("type", "string")
                .put("description", "技能名称；根据系统目录选择与当前任务相关的技能").putArray("enum");
        filesBySkill.keySet().forEach(names::add);
        ArrayNode paths = properties.putObject("file").put("type", "string").put("default", "SKILL.md")
                .put("description", "该技能已打包的文档路径，默认 SKILL.md；不访问任意文件系统").putArray("enum");
        allFiles.forEach(paths::add);
        definitions.add(new CadAiTool("skill_reference", "读取 makeCAD 随版本打包的技能文档。只读、无文件系统访问；先读 SKILL.md，再读任务需要的参考文档。", parameters));
        definitions.add(knowledgeDefinition(json, knowledgePolicy));
        tools = List.copyOf(definitions);
        Map<String, CadAiTool> index = new LinkedHashMap<>();
        for (CadAiTool tool : tools) {
            if (index.put(tool.name(), tool) != null) throw new IOException("Duplicate bundled CAD AI tool name: " + tool.name());
        }
        byName = Map.copyOf(index);
        log.info("CAD AI skills loaded: revision={}, count={}", bundle.path("revision").asText(), skillFiles.size());
    }

    public List<CadAiTool> definitions() { return tools; }

    public List<CadAiTool> definitions(boolean knowledgeEnabled) {
        return tools.stream().filter(tool -> knowledgeEnabled || !"knowledge_lookup".equals(tool.name())).toList();
    }

    public String instructions() { return instructions; }

    static CadAiTool knowledgeDefinition(ObjectMapper json) throws IOException {
        return knowledgeDefinition(json, readKnowledgePolicy(json));
    }

    private static JsonNode readKnowledgePolicy(ObjectMapper json) throws IOException {
        try (InputStream input = new ClassPathResource("cad/ai/knowledge/generation/policy.json").getInputStream()) {
            return json.readTree(input);
        }
    }

    private static CadAiTool knowledgeDefinition(ObjectMapper json, JsonNode policy) throws IOException {
        ObjectNode parameters = json.createObjectNode().put("type", "object").put("additionalProperties", false);
        parameters.putArray("required").add("query");
        ObjectNode properties = parameters.putObject("properties");
        properties.putObject("query").put("type", "string").put("minLength", 1).put("maxLength", 2000)
                .put("description", "当前待建或待改的部件需求；明确保留否定及选配要求，复杂结构可查询已确定的部件");
        ArrayNode typeIds = properties.putObject("type_id").put("type", "string").put("maxLength", 80)
                .put("description", "可选；仅用enum中的稳定ID，未知时省略，由query识别，不猜写ID").putArray("enum");
        JsonNode catalog;
        try (InputStream input = new ClassPathResource("cad/ai/knowledge/generation/catalog.json").getInputStream()) { catalog = json.readTree(input); }
        CadAiKnowledge.validateCatalog(catalog).keySet().stream().sorted().forEach(typeIds::add);
        ObjectNode facts = properties.putObject("facts").put("type", "object").put("additionalProperties", false);
        ObjectNode fields = facts.putObject("properties");
        for (Map.Entry<String, JsonNode> entry : CadAiKnowledge.validateFactDefinitions(catalog).entrySet()) {
            JsonNode definition = entry.getValue();
            ObjectNode field = fields.putObject(entry.getKey()).put("description", definition.path("description").asText()
                    + ("none".equals(definition.path("unit").asText()) ? "" : " (" + definition.path("unit").asText() + ")"));
            field.putArray("type").add(definition.path("type").asText()).add("null");
            if ("string".equals(definition.path("type").asText())) field.put("maxLength", 80);
        }
        Map<String, Map<String, Set<String>>> stringEqualities = new TreeMap<>();
        for (JsonNode document : policy.path("documents")) {
            if ("retired".equals(document.path("status").asText())) continue;
            Iterator<Map.Entry<String, JsonNode>> conditions = document.path("conditions").fields();
            while (conditions.hasNext()) {
                Map.Entry<String, JsonNode> condition = conditions.next();
                JsonNode expected = condition.getValue().path("equals");
                if (expected.isTextual() && fields.has(condition.getKey())) {
                    stringEqualities.computeIfAbsent(condition.getKey(), key -> new TreeMap<>())
                            .computeIfAbsent(expected.asText(), key -> new TreeSet<>()).add(document.path("type_id").asText());
                }
            }
        }
        for (Map.Entry<String, Map<String, Set<String>>> entry : stringEqualities.entrySet()) {
            ObjectNode field = (ObjectNode) fields.path(entry.getKey());
            ArrayNode values = field.putArray("enum");
            List<String> typeGuidance = new ArrayList<>();
            for (Map.Entry<String, Set<String>> equality : entry.getValue().entrySet()) {
                values.add(equality.getKey());
                typeGuidance.add(equality.getKey() + ":" + String.join(",", equality.getValue()));
            }
            values.addNull();
            field.put("description", field.path("description").asText() + "；当前规程登记值/类型：" + String.join("；", typeGuidance)
                    + "。只填已明确采用的值，未知可省略；不代表其他变体受支持。");
        }
        facts.put("description", "仅填用户给定或当前计划明确采用的相关条件；未知可省略或填null。所需条件以查询返回missing为准，不为命中规程擅改需求或默认尺寸。");
        return new CadAiTool("knowledge_lookup", "按需读取齿轮、齿条、蜗轮蜗杆及其机构的专项构造规程，或XZ轴承座筋方向提示。普通基础造型无需查询；只读，沿原通用技能执行。", parameters);
    }

    /** Only schema paths and fixed rule names; never retain argument values in diagnostics. */
    public record ValidationIssue(String rule, String path) {}

    public String diagnosticName(String name) { return name != null && byName.containsKey(name) ? name : "unknown"; }

    public void validateCall(String name, JsonNode arguments) {
        CadAiTool tool = name == null ? null : byName.get(name);
        if (tool == null) throw invalid("unknown_tool", "$");
        if (arguments == null || !arguments.isObject()) throw invalid("object_required", "$");
        ValidationIssue issue = validateSchema(tool.parameters(), arguments, "$", 0);
        if (issue != null) throw invalid(issue.rule(), issue.path());
        if ("skill_reference".equals(name)) {
            Set<String> files = skillFiles.get(arguments.path("skill").asText());
            if (files == null || !files.contains(arguments.path("file").asText("SKILL.md"))) throw invalid("skill_file", "$.file");
        }
        if ("set_parameter".equals(name)) {
            JsonNode value = arguments.get("value");
            JsonNode expression = arguments.get("expression");
            if (value == null && expression == null
                    || value != null && expression != null && !value.asText().equals(expression.asText())) throw invalid("parameter_alias", "$.value");
        }
        if ("screenshot".equals(name) && arguments.has("view") && arguments.has("camera")) throw invalid("view_camera_conflict", "$.camera");
        if ("execute".equals(name)) checkCommand(arguments.path("command").asText(), "$.command");
        if ("batch".equals(name)) {
            int index = 0;
            for (JsonNode step : arguments.path("commands")) {
                String command = step.path("command").asText();
                String path = "$.commands[" + index + "]";
                if (byName.containsKey(command)) {
                    if (Set.of("batch", "screenshot", "check_parameters", "body_topology", "skill_reference", "knowledge_lookup").contains(command)) throw invalid("unsupported_batch_tool", path + ".command");
                    try {
                        validateCall(command, step.has("params") ? step.get("params") : com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.objectNode());
                    } catch (BusinessException error) {
                        if (error.details() instanceof ValidationIssue nested)
                            throw invalid(nested.rule(), path + ".params" + nested.path().substring(1));
                        throw error;
                    }
                } else checkCommand(command, path + ".command");
                index++;
            }
        }
    }

    private void checkCommand(String command, String path) {
        if (!command.matches("[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+")) throw invalid("command_format", path);
        // 后端只做已知危险命令的拒绝；浏览器还必须通过原生 gate，而不能把此处当作完整授权。
        if (command.matches("(file|doc|ui|diagnostics|preferences|settings|app)\\..*")
                || Set.of("view.next_tab", "view.previous_tab", "component.edit_in_place", "component.finish_edit").contains(command))
            throw invalid("command_not_allowed", path);
    }

    private ValidationIssue validateSchema(JsonNode schema, JsonNode value, String path, int depth) {
        if (depth > 32) return new ValidationIssue("schema_depth", path);
        JsonNode type = schema.path("type");
        if (type.isArray()) {
            boolean match = false;
            for (JsonNode choice : type) match |= matches(choice.asText(), value);
            if (!match) return new ValidationIssue("type", path);
        } else if (type.isTextual() && !matches(type.asText(), value)) return new ValidationIssue("type", path);
        if (schema.has("enum")) {
            boolean match = false;
            for (JsonNode choice : schema.path("enum")) match |= choice.equals(value);
            if (!match) return new ValidationIssue("enum", path);
        }
        if (value.isTextual() && (value.asText().length() < schema.path("minLength").asInt(0)
                || value.asText().length() > schema.path("maxLength").asInt(Integer.MAX_VALUE))) return new ValidationIssue("string_length", path);
        if (value.isTextual() && schema.has("pattern") && !value.asText().matches(schema.path("pattern").asText())) return new ValidationIssue("pattern", path);
        if (value.isNumber() && (schema.has("minimum") && value.decimalValue().compareTo(schema.path("minimum").decimalValue()) < 0
                || schema.has("maximum") && value.decimalValue().compareTo(schema.path("maximum").decimalValue()) > 0)) return new ValidationIssue("number_range", path);
        if (value.isObject()) {
            for (JsonNode field : schema.path("required")) if (!value.has(field.asText())) return new ValidationIssue("required", path + "." + field.asText());
            if (value.size() < schema.path("minProperties").asInt(0)) return new ValidationIssue("min_properties", path);
            Iterator<Map.Entry<String, JsonNode>> fields = value.fields();
            while (fields.hasNext()) {
                Map.Entry<String, JsonNode> field = fields.next();
                JsonNode property = schema.path("properties").get(field.getKey());
                JsonNode additional = schema.get("additionalProperties");
                if (property != null) {
                    ValidationIssue issue = validateSchema(property, field.getValue(), path + "." + field.getKey(), depth + 1);
                    if (issue != null) return issue;
                } else if (additional != null && additional.isBoolean() && !additional.asBoolean()) return new ValidationIssue("additional_property", path + ".*");
                else if (additional != null && additional.isObject()) {
                    ValidationIssue issue = validateSchema(additional, field.getValue(), path + ".*", depth + 1);
                    if (issue != null) return issue;
                }
            }
        }
        if (value.isArray()) {
            if (value.size() < schema.path("minItems").asInt(0)) return new ValidationIssue("min_items", path);
            if (value.size() > schema.path("maxItems").asInt(Integer.MAX_VALUE)) return new ValidationIssue("max_items", path);
            if (schema.has("items")) {
                for (int index = 0; index < value.size(); index++) {
                    ValidationIssue issue = validateSchema(schema.path("items"), value.get(index), path + "[" + index + "]", depth + 1);
                    if (issue != null) return issue;
                }
            }
        }
        return null;
    }

    private boolean matches(String type, JsonNode value) {
        return switch (type) {
            case "null" -> value.isNull();
            case "object" -> value.isObject();
            case "array" -> value.isArray();
            case "string" -> value.isTextual();
            case "boolean" -> value.isBoolean();
            case "number" -> value.isNumber();
            case "integer" -> value.isIntegralNumber();
            default -> false;
        };
    }

    private BusinessException invalid(String rule, String path) {
        return new BusinessException(400, "CAD_AI_INVALID_TOOL", "CAD 工具名称或参数不符合协议", new ValidationIssue(rule, path));
    }
}
