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

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.linkerbot.vibemake.service.config.CadAiProperties;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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;

/** Read-only, versioned CAD recipe routing. It never infers dimensions from prose. */
@Component
public class CadAiKnowledge {
    public static final String PROTOCOL = "cad-knowledge-v1";
    public static final String INSTRUCTIONS = "沿原通用技能建模。当前已明确的齿轮、齿条、蜗轮蜗杆及其机构，按需用knowledge_lookup读取已有专项构造规程；XZ草图造轴承座筋时可查询方向风险提示。普通板、轴、螺栓、座体、壳体无需查。仅补齐已明确条件后重查，不改需求凑命中；无适用内容沿原流程，有效上下文已有正文不重复读。用户要求优先于选配示例。";
    private static final Logger log = LoggerFactory.getLogger(CadAiKnowledge.class);
    private static final String RESOURCE_ROOT = "cad/ai/knowledge/";
    private static final Set<String> SPUR_CONDITIONS = Set.of("module_mm", "teeth", "pressure_angle_deg", "profile_shift", "backlash_mm", "addendum_coefficient", "clearance_coefficient", "root_transition");
    private static final List<Pattern> QUALIFIED_GEAR_NAMES = List.of(
            Pattern.compile("(?:(?:内啮合|外啮合|内齿|外齿|内|外|渐开线|直齿|斜齿|螺旋|圆柱|环形|锥齿|圆锥)(?:的\\s*)?\\s*)+(?:齿轮|齿圈|轮)"),
            Pattern.compile("\\b(?:(?:internal|external|involute|spur|helical|bevel|cylindrical|ring)\\s+)+gears?\\b"));
    private static final Pattern UNCERTAIN_NEGATION = Pattern.compile("(?:不能|不得|不可|不允许|不准|不许|不应|不要|不是|并非|禁止|严禁|切勿|请勿|勿|避免|不生成|不创建|不制作|不建)\\s*(?:不|没有|禁止|避免|无\\s*(?:中央|中心)?(?:退刀槽|槽)(?=\\s*(?:[，,。;；\\n]|$)))|\\b(?:not|never|without)\\s+(?:not|no|without|avoid(?:ing)?|excluding|fail\\s+to)\\b");
    private static final Pattern REFERENCE_CREATION = Pattern.compile("(?s).*(?:生成|制作|创建|构造|绘制|建模|只造|只做|做|造|建|画|当前待修改部件是|\\bmake|\\bcreate|\\bbuild|\\bmodel|\\bgenerate|\\bdraw)\\s*(?:一个|一件|一套|一只|一条|a\\b|an\\b|the\\b)?\\s*$");
    private static final Pattern TARGET_INTENT = Pattern.compile("生成|制作|创建|构造|绘制|建模|只造|只做|修改|只查询|只查|当前待(?:建|修改)部件是|\\b(?:make|create|build|model|generate|draw|modify)\\b");
    private static final Pattern JOINED_TARGET = Pattern.compile("(?s).*(?:和|与|及|以及|并|同时|另|再|\\band|\\balso)\\s*$");
    private static final Pattern SHAFT_INTERFACE = Pattern.compile("齿轮(?:安装)?孔(?=\\s*(?:名义)?(?:直径|孔径|尺寸|为|=|[:：])?\\s*\\d)");
    private static final String REFERENCE_MODIFIERS = "(?:(?![，,。;；\\r\\n]|生成|制作|创建|构造|绘制|建模|修改|另|再|并|和|与|以及|\\b(?:create|build|generate|make|modify|and|also)\\b).){0,128}?";
    private final ObjectMapper json;
    private final CadAiProperties properties;
    private final Map<String, JsonNode> types;
    private final Map<String, JsonNode> factDefinitions;
    private final List<Recipe> recipes;
    private final Pattern referenceNames;
    private final Pattern companionNames;

    private record Recipe(JsonNode metadata, String text) {}
    private record QualifiedGearName(String name, String type, int start, int end, boolean conflict) {}

    @Autowired
    public CadAiKnowledge(ObjectMapper json, CadAiProperties properties) throws IOException {
        this(json, properties, readPolicy(json));
    }

    // Explicit policy keeps historical routing fixtures reproducible after utility withdrawals.
    CadAiKnowledge(ObjectMapper json, CadAiProperties properties, JsonNode policy) throws IOException {
        this.json = json;
        this.properties = properties;
        JsonNode catalog = read("generation/catalog.json");
        types = validateCatalog(catalog);
        referenceNames = referenceNames(types);
        companionNames = Pattern.compile("(?:配套|匹配)" + REFERENCE_MODIFIERS + objectNames(types)
                + "(?=\\s*(?:的\\s*)?(?:中心距|轴向模数|法向模数|端面模数|模数|轴向压力角|压力角|分度(?:圆)?(?:直径|径)|孔径|轴径|安装孔|中心高|接口|配合))");
        factDefinitions = validateFactDefinitions(catalog);
        recipes = validateRecipes(policy);
        log.info("CAD knowledge loaded: version={}, types={}, recipes={}", catalog.path("version").asText(), types.size(), recipes.size());
    }

    private static JsonNode readPolicy(ObjectMapper json) throws IOException {
        try (InputStream input = new ClassPathResource(RESOURCE_ROOT + "generation/policy.json").getInputStream()) {
            return json.readTree(input);
        }
    }

    private JsonNode read(String path) throws IOException {
        try (InputStream input = new ClassPathResource(RESOURCE_ROOT + path).getInputStream()) {
            return json.readTree(input);
        }
    }

    static Map<String, JsonNode> validateCatalog(JsonNode catalog) throws IOException {
        if (catalog == null || catalog.path("schema_version").asInt() != 1 || !catalog.path("types").isArray())
            throw new IOException("Invalid CAD knowledge catalog");
        Map<String, JsonNode> index = new LinkedHashMap<>();
        Set<String> registeredAliases = new HashSet<>();
        for (JsonNode type : catalog.path("types")) {
            String id = type.path("id").asText();
            if (!id.matches("[a-z][a-z0-9-]{1,79}") || index.put(id, type) != null
                    || type.path("name_zh").asText().isBlank() || !type.path("aliases").isArray()
                    || !Set.of("group", "part", "mechanism").contains(type.path("kind").asText()))
                throw new IOException("Invalid or duplicate CAD knowledge type");
            Set<String> aliases = new HashSet<>();
            for (JsonNode alias : type.path("aliases"))
                if (!alias.isTextual() || alias.asText().isBlank() || !aliases.add(alias.asText()) || !registeredAliases.add(alias.asText().toLowerCase(Locale.ROOT)))
                    throw new IOException("Invalid CAD knowledge alias");
        }
        for (String id : index.keySet()) {
            Set<String> visited = new HashSet<>();
            String cursor = id;
            while (cursor != null) {
                if (!visited.add(cursor) || !index.containsKey(cursor)) throw new IOException("Broken or cyclic CAD knowledge hierarchy");
                JsonNode parent = index.get(cursor).get("parent");
                cursor = parent == null || parent.isNull() ? null : parent.asText();
            }
            for (JsonNode related : index.get(id).path("related_types"))
                if (!index.containsKey(related.asText())) throw new IOException("Broken CAD knowledge type reference");
        }
        if (index.isEmpty()) throw new IOException("Empty CAD knowledge catalog");
        return Map.copyOf(index);
    }

    /** Canonical property dictionary shared by tool schemas and recipe eligibility. */
    static Map<String, JsonNode> validateFactDefinitions(JsonNode catalog) throws IOException {
        JsonNode definitions = catalog.path("fact_definitions");
        if (!definitions.isObject() || definitions.isEmpty() || definitions.size() > 64)
            throw new IOException("Invalid CAD knowledge property dictionary");
        Map<String, JsonNode> result = new TreeMap<>();
        Iterator<Map.Entry<String, JsonNode>> entries = definitions.fields();
        while (entries.hasNext()) {
            Map.Entry<String, JsonNode> entry = entries.next();
            JsonNode definition = entry.getValue();
            if (!entry.getKey().matches("[a-z][a-z0-9_]{0,63}") || !definition.isObject()
                    || !Set.of("number", "string", "boolean").contains(definition.path("type").asText())
                    || !Set.of("mm", "deg", "count", "none").contains(definition.path("unit").asText())
                    || !definition.path("description").isTextual() || definition.path("description").asText().isBlank()
                    || definition.path("description").asText().length() > 160)
                throw new IOException("Invalid CAD knowledge property definition");
            result.put(entry.getKey(), definition);
        }
        return Collections.unmodifiableMap(result);
    }

    private List<Recipe> validateRecipes(JsonNode policy) throws IOException {
        if (policy == null || policy.path("schema_version").asInt() != 1 || !policy.path("documents").isArray())
            throw new IOException("Invalid CAD knowledge policy");
        Set<String> ids = new HashSet<>();
        List<Recipe> result = new ArrayList<>();
        for (JsonNode document : policy.path("documents")) {
            String id = document.path("doc_id").asText();
            String path = document.path("path").asText();
            String hash = document.path("sha256").asText();
            if (!id.matches("[a-z][a-z0-9-]+") || !ids.add(id)
                    || !document.path("version").asText().matches("\\d+\\.\\d+\\.\\d+")
                    || !Set.of("retired", "experimental", "approved").contains(document.path("status").asText())
                    || !path.matches("generation/(candidates|archive)/[a-z0-9-]+\\.md")
                    || !hash.matches("[a-f0-9]{64}")) throw new IOException("Invalid CAD knowledge recipe metadata");
            validatePublication(document);
            byte[] bytes;
            try (InputStream input = new ClassPathResource(RESOURCE_ROOT + path).getInputStream()) { bytes = input.readAllBytes(); }
            verifyHash(bytes, hash);
            if (bytes.length == 0 || bytes.length > 24 * 1024) throw new IOException("CAD knowledge recipe body exceeds transport budget");
            if ("retired".equals(document.path("status").asText())) continue;
            String role = document.path("content_role").asText("recipe");
            if (!Set.of("recipe", "risk_hint").contains(role)) throw new IOException("Invalid CAD knowledge content role");
            validateActivation(document.path("activation"));
            if (!types.containsKey(document.path("type_id").asText()) || !document.path("conditions").isObject()
                    || document.path("conditions").isEmpty() && !("risk_hint".equals(role) && document.has("activation")))
                throw new IOException("Incomplete CAD knowledge recipe eligibility");
            if (!document.path("conditions").isEmpty())
                validateConditions(document.path("type_id").asText(), document.path("conditions"), factDefinitions);
            result.add(new Recipe(document, new String(bytes, StandardCharsets.UTF_8)));
        }
        return List.copyOf(result);
    }

    private static void validateActivation(JsonNode activation) throws IOException {
        if (activation.isMissingNode()) return;
        if (!activation.isObject() || activation.size() != 2)
            throw new IOException("Invalid CAD knowledge activation");
        for (String field : List.of("all_terms", "any_terms")) {
            JsonNode terms = activation.path(field);
            if (!terms.isArray() || terms.isEmpty() || terms.size() > 8)
                throw new IOException("Invalid CAD knowledge activation terms");
            Set<String> unique = new HashSet<>();
            for (JsonNode term : terms)
                if (!term.isTextual() || term.asText().isBlank() || term.asText().length() > 40
                        || !term.asText().equals(term.asText().strip().toLowerCase(Locale.ROOT)) || !unique.add(term.asText()))
                    throw new IOException("Invalid CAD knowledge activation term");
        }
    }

    private static boolean activationMatches(JsonNode activation, String query) {
        if (activation.isMissingNode()) return true;
        // Keep operation terms together: a housing name containing 筋 must not activate an XZ bore operation.
        for (String clause : query.split("[，,。;；\\n]")) {
            boolean all = true;
            for (JsonNode term : activation.path("all_terms")) if (!hasActivationTerm(clause, term.asText())) all = false;
            if (!all) continue;
            for (JsonNode term : activation.path("any_terms")) if (hasActivationTerm(clause, term.asText())) return true;
        }
        return false;
    }

    private static boolean hasActivationTerm(String query, String term) {
        if (term.matches("[a-z0-9_]+"))
            return Pattern.compile("(?<![a-z0-9_])" + Pattern.quote(term) + "(?![a-z0-9_])").matcher(query).find();
        return query.contains(term);
    }

    static void validatePublication(JsonNode document) throws IOException {
        if (!"approved".equals(document.path("status").asText())) return;
        JsonNode evidence = document.path("evidence");
        if (!"benefit_observed".equals(evidence.path("verdict").asText()))
            throw new IOException("Approved CAD knowledge recipe lacks benefit evidence");
        for (String field : List.of("engine_replay", "ab_comparison", "parameter_transfer")) {
            JsonNode reference = evidence.path(field);
            if (reference.isTextual() && !reference.asText().isBlank()) continue;
            if (!reference.isArray() || reference.isEmpty()) throw new IOException("Approved CAD knowledge recipe lacks evidence references");
            for (JsonNode item : reference)
                if (!item.isTextual() || item.asText().isBlank()) throw new IOException("Invalid approved CAD knowledge evidence reference");
        }
    }

    static void validateConditions(String type, JsonNode conditions) throws IOException {
        try (InputStream input = new ClassPathResource(RESOURCE_ROOT + "generation/catalog.json").getInputStream()) {
            validateConditions(type, conditions, validateFactDefinitions(new ObjectMapper().readTree(input)));
        }
    }

    private static void validateConditions(String type, JsonNode conditions, Map<String, JsonNode> definitions) throws IOException {
        if (!conditions.isObject() || conditions.isEmpty()) throw new IOException("Empty CAD recipe conditions");
        Set<String> present = new HashSet<>();
        Iterator<Map.Entry<String, JsonNode>> entries = conditions.fields();
        while (entries.hasNext()) {
            Map.Entry<String, JsonNode> entry = entries.next();
            JsonNode rule = entry.getValue();
            JsonNode definition = definitions.get(entry.getKey());
            if (definition == null || !rule.isObject() || rule.isEmpty()) throw new IOException("Invalid CAD recipe condition");
            present.add(entry.getKey());
            if (!"number".equals(definition.path("type").asText())) {
                JsonNode expected = rule.path("equals");
                if (rule.size() != 1 || "string".equals(definition.path("type").asText())
                        && (!expected.isTextual() || expected.asText().isBlank() || expected.asText().length() > 80)
                        || "boolean".equals(definition.path("type").asText()) && !expected.isBoolean())
                    throw new IOException("Invalid CAD recipe property equality");
                continue;
            }
            Iterator<Map.Entry<String, JsonNode>> rules = rule.fields();
            while (rules.hasNext()) {
                Map.Entry<String, JsonNode> field = rules.next();
                if (!Set.of("min", "max", "min_exclusive", "abs_min", "abs_max", "equals", "integer").contains(field.getKey())
                        || "integer".equals(field.getKey()) && !field.getValue().isBoolean()
                        || !"integer".equals(field.getKey()) && (!field.getValue().isNumber() || !Double.isFinite(field.getValue().asDouble())))
                    throw new IOException("Invalid CAD recipe numeric condition");
            }
            if (rule.has("min") && rule.has("min_exclusive")) throw new IOException("Duplicate CAD recipe lower bound");
            double lower = rule.path("min").asDouble(rule.path("min_exclusive").asDouble(Double.NEGATIVE_INFINITY));
            double upper = rule.path("max").asDouble(Double.POSITIVE_INFINITY);
            if (lower > upper || rule.has("min_exclusive") && lower == upper) throw new IOException("Empty CAD recipe range");
            double absoluteLower = rule.path("abs_min").asDouble(0);
            double absoluteUpper = rule.path("abs_max").asDouble(Double.POSITIVE_INFINITY);
            if (absoluteLower < 0 || absoluteUpper < absoluteLower
                    || !rangesIntersect(lower, upper, rule.has("min_exclusive"), absoluteLower, absoluteUpper)
                    && !rangesIntersect(lower, upper, rule.has("min_exclusive"), -absoluteUpper, -absoluteLower))
                throw new IOException("Empty CAD recipe absolute range");
            if (rule.has("equals") && !numericConditionMatches(rule, rule.path("equals").asDouble()))
                throw new IOException("Conflicting CAD recipe equality");
        }
        if ("involute-spur-gear".equals(type) && !present.containsAll(SPUR_CONDITIONS))
            throw new IOException("Missing dependent involute spur gear conditions");
    }

    private static boolean rangesIntersect(double lower, double upper, boolean lowerExclusive, double otherLower, double otherUpper) {
        double start = Math.max(lower, otherLower);
        double end = Math.min(upper, otherUpper);
        return start < end || start == end && !(lowerExclusive && start == lower);
    }

    private static boolean numericConditionMatches(JsonNode rule, double number) {
        return Double.isFinite(number)
                && (!rule.has("equals") || Math.abs(number - rule.path("equals").asDouble()) < 1e-9)
                && (!rule.has("min") || number >= rule.path("min").asDouble())
                && (!rule.has("max") || number <= rule.path("max").asDouble())
                && (!rule.has("min_exclusive") || number > rule.path("min_exclusive").asDouble())
                && (!rule.has("abs_min") || Math.abs(number) >= rule.path("abs_min").asDouble())
                && (!rule.has("abs_max") || Math.abs(number) <= rule.path("abs_max").asDouble())
                && (!rule.path("integer").asBoolean() || number == Math.rint(number));
    }

    static void verifyHash(byte[] bytes, String expected) throws IOException {
        try {
            String actual = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
            if (!actual.equals(expected)) throw new IOException("CAD knowledge recipe hash mismatch");
        } catch (NoSuchAlgorithmException error) { throw new IOException("SHA-256 unavailable", error); }
    }

    public ObjectNode lookup(JsonNode arguments, String build) {
        if ("off".equals(properties.getKnowledgeMode())) return answer("disabled", null, "专项知识已关闭；继续原助手流程，结果待验证。");
        String original = arguments.path("query").asText();
        if (original.toLowerCase(Locale.ROOT).matches("(?s)\\s*(?:解释|介绍|说明原理|比较|什么是|查询历史|explain|what is|compare|describe the principle).*"))
            return answer("not_applicable", null, "此为说明或比较请求，无需加载建模规程；沿原助手回答。");
        if (UNCERTAIN_NEGATION.matcher(currentPartQuery(original)).find())
            return answer("ambiguous", null, "当前描述含双重否定或禁止范围不明确；先确认当前部件，不据此删除候选或加载规程。");
        String query = positiveQuery(original);
        if (query.isBlank()) return answer("ambiguous", null, "未确定当前待建部件；不加载被否定的规程。");
        String selected = arguments.path("type_id").asText();
        if (qualifiedGearNames(query).stream().anyMatch(QualifiedGearName::conflict))
            return answer("ambiguous", selected.isBlank() ? null : selected, "当前内齿描述未明确为受支持的直齿类型，或包含冲突的内外齿限定；不加载相近规程。");
        List<String> matches = coalesceMechanismComponents(candidates(query), selected);
        matches = coalesceQualifiedPairName(query, matches, selected);
        matches = coalesceSamePartNames(query, matches, selected);
        if (!selected.isBlank() && !matches.contains(selected) && candidates(original.toLowerCase(Locale.ROOT)).contains(selected)
                && !query.equals(original.toLowerCase(Locale.ROOT)))
            return answer("ambiguous", selected, "指定类型仅出现在被否定或非当前部件的文字中；不加载该规程。");
        if (!selected.isBlank() && !types.containsKey(selected)) {
            ObjectNode result = answer(matches.isEmpty() ? "uncovered" : "ambiguous", selected,
                    matches.isEmpty() ? "该类型未登记；继续原助手尝试，结果待验证。" : "指定ID未登记；query已命中候选，可省略type_id或使用返回的稳定ID重查。");
            result.set("candidates", json.valueToTree(matches));
            return result;
        }
        if (!selected.isBlank() && !matches.isEmpty() && !matches.contains(selected))
            return answer("ambiguous", selected, "查询文字与指定类型不一致；请按当前部件确认类型，不能套用相近规程。");
        if (selected.isBlank()) {
            if (matches.size() != 1) return answer("ambiguous", null, "类型未明确；只为当前已确定的部件查询，不据传动角度猜齿制。").set("candidates", json.valueToTree(matches));
            selected = matches.getFirst();
        }
        if (matches.size() > 1) return answer("ambiguous", selected, "包含不同类型；请仅查询当前确定的部件，不能合并加载相近规程。").set("candidates", json.valueToTree(matches));
        JsonNode type = types.get(selected);
        String conflictQuery = typeConflictQuery(selected, query);
        for (JsonNode term : type.path("disqualifying_terms"))
            if (conflictQuery.contains(term.asText().toLowerCase(Locale.ROOT)))
                return answer("ambiguous", selected, "当前描述包含与该类型冲突的齿制信息；先区分类型，不加载近似规程。");
        if (selected.endsWith("unspecified")) return answer("ambiguous", selected, "尚需区分齿线、节面或内外齿；不加载任何近似规程。").set("candidates", type.path("related_types"));
        String finalSelected = selected;
        List<Recipe> eligible = recipes.stream().filter(recipe -> finalSelected.equals(recipe.metadata().path("type_id").asText()))
                .filter(recipe -> "approved".equals(recipe.metadata().path("status").asText()) || "pilot".equals(properties.getKnowledgeMode()) && "experimental".equals(recipe.metadata().path("status").asText())).toList();
        if (eligible.isEmpty()) {
            if ("mechanism".equals(type.path("kind").asText()))
                return answer("uncovered", selected, "暂无机构规程；沿原流程设计，确定各部件类型后可分别查询，结果待验证。")
                        .set("related_types", type.path("related_types"));
            return answer("uncovered", selected, "该类型暂无已准入规程；继续原助手尝试，结果待验证，勿套用相近齿制规程。");
        }
        List<Recipe> activated = eligible.stream().filter(recipe -> activationMatches(recipe.metadata().path("activation"), query)).toList();
        if (activated.isEmpty()) return answer("not_applicable", selected, "当前操作无需额外提示；沿原通用技能继续，无需补参重查。");
        JsonNode facts = arguments.path("facts");
        List<Recipe> applicable = new ArrayList<>();
        List<String> missing = new ArrayList<>();
        List<String> conflicts = new ArrayList<>();
        for (Recipe recipe : activated) {
            List<String> absent = new ArrayList<>();
            List<String> invalid = new ArrayList<>();
            checkConditions(selected, recipe.metadata().path("conditions"), facts, absent, invalid);
            if (absent.isEmpty() && invalid.isEmpty()) applicable.add(recipe);
            missing.addAll(absent);
            conflicts.addAll(invalid);
        }
        if (applicable.size() > 1) return answer("ambiguous", selected, "存在多个适用规程；需区分其变体条件，不自动选择相似项。");
        if (applicable.isEmpty()) {
            ObjectNode result = answer(conflicts.isEmpty() ? "needs_conditions" : "uncovered", selected,
                    conflicts.isEmpty() ? "正文未返回，尚未取得构造规程；仅当missing条件已明确采用时补齐并重查，不能据本结果声称已读取或适用。不为命中改变用户要求。" : "已给条件超出规程范围；继续原助手尝试，结果待验证，不自动改值。");
            result.set("missing", json.valueToTree(missing.stream().distinct().toList()));
            result.set("conflicts", json.valueToTree(conflicts.stream().distinct().toList()));
            result.set("supported_conditions", activated.getFirst().metadata().path("conditions"));
            return result;
        }
        Recipe recipe = applicable.getFirst();
        String role = recipe.metadata().path("content_role").asText("recipe");
        ObjectNode result = answer("matched", selected, "risk_hint".equals(role)
                ? "仅提示当前操作的已知风险，不是完整构造规程；新精简文本的模型收益未验证。"
                : "适用当前部件；选配按用户要求，按正文表示与验证边界执行。");
        result.putArray("documents").addObject().put("id", recipe.metadata().path("doc_id").asText())
                .put("version", recipe.metadata().path("version").asText()).put("sha256", recipe.metadata().path("sha256").asText())
                .put("status", recipe.metadata().path("status").asText()).put("content_role", role).put("text", recipe.text());
        log.info("CAD knowledge matched: type={}, recipe={}, version={}", selected, recipe.metadata().path("doc_id").asText(), recipe.metadata().path("version").asText());
        return result;
    }

    private ObjectNode answer(String status, String type, String reason) {
        ObjectNode result = json.createObjectNode().put("status", status).put("reason", reason);
        if (type != null) result.put("type_id", type);
        result.putArray("documents");
        result.putArray("missing");
        return result;
    }

    private static boolean contains(JsonNode array, String value) {
        for (JsonNode item : array) if (item.asText().equals(value)) return true;
        return false;
    }

    static void checkConditions(String type, JsonNode conditions, JsonNode facts, List<String> missing, List<String> conflicts) {
        Iterator<Map.Entry<String, JsonNode>> entries = conditions.fields();
        while (entries.hasNext()) {
            Map.Entry<String, JsonNode> entry = entries.next();
            String name = entry.getKey();
            JsonNode value = facts.get(name);
            if (value == null || value.isNull()) { missing.add(name); continue; }
            JsonNode rule = entry.getValue();
            boolean valid;
            if (rule.path("equals").isTextual() || rule.path("equals").isBoolean()) valid = rule.path("equals").equals(value);
            else {
                double number = value.asDouble(Double.NaN);
                valid = value.isNumber() && numericConditionMatches(rule, number);
            }
            if (!valid) conflicts.add(name);
        }
        if ("involute-spur-gear".equals(type) && missing.isEmpty() && conflicts.isEmpty()) {
            double module = facts.path("module_mm").asDouble();
            double teeth = facts.path("teeth").asDouble();
            double radius = module * teeth / 2;
            double root = radius - (facts.path("addendum_coefficient").asDouble() + facts.path("clearance_coefficient").asDouble()) * module;
            double base = radius * Math.cos(Math.toRadians(facts.path("pressure_angle_deg").asDouble()));
            if (!Double.isFinite(root) || !Double.isFinite(base) || root <= 0 || root >= base) conflicts.add("root_radius_must_be_positive_and_below_base_radius");
        }
        if (!missing.isEmpty() || !conflicts.isEmpty()) return;
        if ("internal-spur-gear".equals(type) && hasConditions(conditions, "module_mm", "teeth", "pressure_angle_deg", "outer_radius_mm")) {
            double module = facts.path("module_mm").asDouble();
            double pitch = module * facts.path("teeth").asDouble() / 2;
            double root = pitch + 1.25 * module;
            double tip = pitch - module;
            double base = pitch * Math.cos(Math.toRadians(facts.path("pressure_angle_deg").asDouble()));
            double outer = facts.path("outer_radius_mm").asDouble();
            if (!Double.isFinite(root) || !Double.isFinite(tip) || !Double.isFinite(base)
                    || !(outer > root && root > tip && tip > base && base > 0))
                conflicts.add("internal_radii_must_satisfy_outer_gt_root_gt_tip_gt_base_gt_zero");
        }
        if (Set.of("helical-cylindrical-gear", "herringbone-gear", "double-helical-gear").contains(type)
                && hasConditions(conditions, "normal_module_mm", "teeth", "normal_pressure_angle_deg", "helix_angle_deg")) {
            double module = facts.path("normal_module_mm").asDouble();
            double cosine = Math.cos(Math.toRadians(facts.path("helix_angle_deg").asDouble()));
            double pitch = module / cosine * facts.path("teeth").asDouble() / 2;
            double pressure = Math.atan(Math.tan(Math.toRadians(facts.path("normal_pressure_angle_deg").asDouble())) / cosine);
            double root = pitch - 1.25 * module;
            double base = pitch * Math.cos(pressure);
            double tip = pitch + module;
            if (!Double.isFinite(root) || !Double.isFinite(base) || !Double.isFinite(tip)
                    || !(root > 0 && root < base && base < tip))
                conflicts.add("helical_radii_must_satisfy_zero_lt_root_lt_base_lt_tip");
        }
        if (Set.of("herringbone-gear", "double-helical-gear").contains(type)
                && hasConditions(conditions, "central_gap_mm", "face_width_mm")) {
            double gap = facts.path("central_gap_mm").asDouble();
            double width = facts.path("face_width_mm").asDouble();
            if (!(gap >= 0 && gap < width)) conflicts.add("central_gap_must_leave_two_positive_width_arms");
        }
        if ("hex-head-bolt".equals(type)
                && hasConditions(conditions, "nominal_diameter_mm", "under_head_length_mm", "across_flats_mm", "thread_length_mm")) {
            if (!(facts.path("across_flats_mm").asDouble() > facts.path("nominal_diameter_mm").asDouble()
                    && facts.path("thread_length_mm").asDouble() <= facts.path("under_head_length_mm").asDouble()))
                conflicts.add("hex_head_must_exceed_shank_and_thread_region_stay_below_head");
        }
        if ("ribbed-bearing-housing".equals(type) && hasConditions(conditions, "center_height_mm", "base_thickness_mm",
                "boss_outer_diameter_mm", "bore_diameter_mm", "pedestal_width_mm", "rib_height_mm", "min_wall_mm")) {
            double center = facts.path("center_height_mm").asDouble();
            double base = facts.path("base_thickness_mm").asDouble();
            double outer = facts.path("boss_outer_diameter_mm").asDouble();
            double bore = facts.path("bore_diameter_mm").asDouble();
            double wall = facts.path("min_wall_mm").asDouble();
            if (!(center - outer / 2 >= base && center - bore / 2 - base >= wall
                    && (outer - bore) / 2 >= wall && facts.path("pedestal_width_mm").asDouble() < outer
                    && facts.path("rib_height_mm").asDouble() <= center - base))
                conflicts.add("bearing_boss_pedestal_rib_and_bore_material_outside_recipe_domain");
        }
        if ("covered-thin-wall-enclosure".equals(type) && hasConditions(conditions, "length_mm", "width_mm", "height_mm",
                "wall_thickness_mm", "bottom_thickness_mm", "lid_thickness_mm", "fastener_inset_mm",
                "boss_outer_diameter_mm", "boss_height_mm", "pilot_depth_mm", "rib_height_mm", "min_wall_mm")) {
            double length = facts.path("length_mm").asDouble();
            double width = facts.path("width_mm").asDouble();
            double height = facts.path("height_mm").asDouble();
            double wall = facts.path("wall_thickness_mm").asDouble();
            double bottom = facts.path("bottom_thickness_mm").asDouble();
            double boss = facts.path("boss_height_mm").asDouble();
            double diameter = facts.path("boss_outer_diameter_mm").asDouble();
            double inset = facts.path("fastener_inset_mm").asDouble();
            double minimum = facts.path("min_wall_mm").asDouble();
            if (!(length > 2 * wall && width > 2 * wall && bottom < height && bottom + boss <= height
                    && facts.path("pilot_depth_mm").asDouble() < boss && facts.path("rib_height_mm").asDouble() <= boss
                    && inset - wall > diameter / 2 && length - 2 * inset > diameter && width - 2 * inset > diameter
                    && wall >= minimum && bottom >= minimum && facts.path("lid_thickness_mm").asDouble() >= minimum))
                conflicts.add("case_cavity_boss_blind_depth_fastener_or_wall_outside_recipe_domain");
        }
        if (Set.of("straight-bevel-gear", "spiral-bevel-gear").contains(type)
                && hasConditions(conditions, "module_mm", "teeth", "cone_angle_deg", "axial_height_mm", "geometry_representation")) {
            double radius = facts.path("module_mm").asDouble() * facts.path("teeth").asDouble() / 2;
            double apexHeight = radius / Math.tan(Math.toRadians(facts.path("cone_angle_deg").asDouble()));
            double endScale = 1 - facts.path("axial_height_mm").asDouble() / apexHeight;
            if (!Double.isFinite(radius) || !Double.isFinite(apexHeight) || !Double.isFinite(endScale)
                    || !(endScale >= 0.45 && endScale <= 0.9))
                conflicts.add("bevel_end_scale_must_be_between_045_and_09");
        }
        if ("worm".equals(type) && hasConditions(conditions, "axial_module_mm", "pitch_diameter_mm", "worm_starts", "axial_length_mm")) {
            double module = facts.path("axial_module_mm").asDouble();
            double root = facts.path("pitch_diameter_mm").asDouble() / 2 - 1.25 * module;
            double pitch = Math.PI * module;
            double lead = facts.path("worm_starts").asDouble() * pitch;
            double length = facts.path("axial_length_mm").asDouble();
            double turns = (length + 2 * lead) / lead;
            if (!Double.isFinite(root) || !Double.isFinite(pitch) || !Double.isFinite(lead) || !Double.isFinite(turns)
                    || !(root > 0.1 * module && length >= pitch && turns <= 200))
                conflicts.add("worm_core_length_and_turns_outside_recipe_domain");
        }
        if ("worm-wheel".equals(type) && hasConditions(conditions, "module_mm", "teeth", "pressure_angle_deg", "pitch_diameter_mm", "face_width_mm", "geometry_representation")) {
            double module = facts.path("module_mm").asDouble();
            double pitch = module * facts.path("teeth").asDouble() / 2;
            double wormRadius = facts.path("pitch_diameter_mm").asDouble() / 2;
            double halfWidth = facts.path("face_width_mm").asDouble() / 2;
            double major = pitch + wormRadius;
            double minor = wormRadius - module;
            double base = pitch * Math.cos(Math.toRadians(facts.path("pressure_angle_deg").asDouble()));
            double midRadius = major - minor;
            double radicand = minor * minor - halfWidth * halfWidth;
            double endRadius = major - Math.sqrt(radicand);
            double blankTip = pitch + 1.5 * module;
            if (!Double.isFinite(base) || !Double.isFinite(midRadius) || !Double.isFinite(radicand)
                    || !Double.isFinite(endRadius) || !Double.isFinite(blankTip)
                    || !(minor > halfWidth && halfWidth > 0 && base < midRadius && midRadius < endRadius
                    && endRadius < blankTip - 0.005 * module))
                conflicts.add("worm_wheel_throat_outside_recipe_domain");
        }
    }

    private static boolean hasConditions(JsonNode conditions, String... names) {
        for (String name : names) if (!conditions.has(name)) return false;
        return true;
    }

    private static String currentPartQuery(String query) {
        return query.toLowerCase(Locale.ROOT).replaceFirst("(?s)^.*(当前只造|当前只做|当前待修改部件是|中先做|只造)", "$1");
    }

    private static String typeConflictQuery(String type, String query) {
        // A clause declaring absent optional features does not assert those features.
        // Do not cross a positive replacement, independent target, or clause boundary.
        String focused = query;
        if (Set.of("mounting-plate", "covered-thin-wall-enclosure").contains(type))
            focused = query.replaceAll("(^|[，,。;；\\s])(?:无|没有|不加|不设(?:置)?|不含|不包含|不带|不留)[^，,。;；\\n\\d]*?(?=，|,|。|;|；|\\n|但|而|仍|却|保留|改用|改成|换成|另(?:做|加|有|带|留)|或(?:有|带|保留|生成)|$)", "$1");
        if (!"herringbone-gear".equals(type)) return focused;
        // Absence and a literal zero-width attribute are not a grooved tooth structure.
        // Scope to complete attribute clauses; keep positive/uncertain conflicts and facts.
        return focused.replaceAll("(^|[，,。;；\\s])(?:无|没有|不带|不设(?:置)?|不含|不留)\\s*(?:中央|中心)?\\s*(?:退刀槽|槽)(?=\\s*(?:[，,。;；\\n]|$))", "$1")
                .replaceAll("(^|[，,。;；\\s])(?:中央|中心)?(?:退刀)?槽(?:的)?(?:轴向)?宽(?:度)?\\s*(?:为|等于|=|:|：)?\\s*0(?:\\.0+)?(?![\\d.])\\s*(?:mm|毫米)?(?=\\s*(?:[，,。;；\\n]|$))", "$1")
                .replaceAll("\\bno\\s+(?:a\\s+)?(?:central\\s+)?(?:groove|gap)\\b(?=\\s*(?:[,.;]|$))", " ")
                .replaceAll("\\b(?:central\\s+)?(?:gap|groove)(?:\\s+width)?\\s*(?:=|:|is|of)?\\s*0(?:\\.0+)?(?![\\d.])\\s*(?:mm)?(?=\\s*(?:[,.;]|$))", " ");
    }

    private String positiveQuery(String query) {
        // A prohibited substitution stays negative through its entire clause. A verb such
        // as “用” or “改成” inside that clause does not introduce a positive alternative.
        String focused = currentPartQuery(query).replaceAll("(?:不得|禁止|严禁|不可|不能|切勿|请勿|勿|不允许|不准|不许|不应|避免|不要(?:将|把|使用|采用|用|以|拿)|\\b(?:do|must|should)\\s+not\\b|\\bnever\\b)[^，,。;；\\n]*", " ");
        // Simple rejected alternatives can still precede an explicit replacement marker.
        focused = focused.replaceAll("(?:不要|不是|不用|不做|不造|不需要|不生成|不创建|不制作|不建|改掉|\\bwithout\\b|\\bnot\\b)[^，,。;；\\n]*?(?=，|,|。|;|；|\\n|改用|换成|改成|而是|但(?:要)?(?:生成|制作|创建|构造)|$)", " ");
        Matcher references = referenceNames.matcher(focused);
        StringBuilder positive = new StringBuilder();
        while (references.find()) {
            // A reference object is not a creation target, unless the request explicitly
            // creates that reference object. Keep dimensions as prose, never infer facts.
            boolean created = REFERENCE_CREATION.matcher(focused.substring(0, references.start())).matches();
            references.appendReplacement(positive, created ? Matcher.quoteReplacement(references.group()) : " ");
        }
        references.appendTail(positive);
        focused = positive.toString();
        Matcher companions = companionNames.matcher(focused);
        positive = new StringBuilder();
        while (companions.find()) {
            String prefix = focused.substring(0, companions.start());
            List<String> targets = candidates(prefix);
            List<String> referencesOnly = candidates(companions.group());
            // A companion with an interface dimension is a reference only after one
            // explicit, different target. Joined or independently created parts remain.
            boolean reference = targets.size() == 1 && !referencesOnly.contains(targets.getFirst())
                    && TARGET_INTENT.matcher(prefix).find() && !JOINED_TARGET.matcher(prefix).matches()
                    && !REFERENCE_CREATION.matcher(prefix).matches()
                    && !TARGET_INTENT.matcher(focused.substring(companions.end()).split("[，,。;；\\r\\n]", 2)[0]).find();
            companions.appendReplacement(positive, reference ? " " : Matcher.quoteReplacement(companions.group()));
        }
        companions.appendTail(positive);
        focused = positive.toString();
        Matcher interfaces = SHAFT_INTERFACE.matcher(focused);
        positive = new StringBuilder();
        while (interfaces.find()) {
            String prefix = focused.substring(0, interfaces.start());
            boolean reference = candidates(prefix).equals(List.of("stepped-shaft"))
                    && TARGET_INTENT.matcher(prefix).find() && !JOINED_TARGET.matcher(prefix).matches()
                    && !REFERENCE_CREATION.matcher(prefix).matches();
            interfaces.appendReplacement(positive, reference ? "配合孔" : Matcher.quoteReplacement(interfaces.group()));
        }
        interfaces.appendTail(positive);
        return positive.toString();
    }

    private static Pattern referenceNames(Map<String, JsonNode> types) {
        String object = objectNames(types);
        return Pattern.compile("(?:参考" + REFERENCE_MODIFIERS + object
                + "|\\breference\\s+(?:(?:existing|known)\\s+)?" + object
                + "|" + object + "\\s*(?:仅作为|只作为|作为|仅供|只供)\\s*参考)");
    }

    private static String objectNames(Map<String, JsonNode> types) {
        Set<String> names = new HashSet<>();
        for (JsonNode type : types.values()) for (JsonNode alias : type.path("aliases")) names.add(alias.asText().toLowerCase(Locale.ROOT));
        String alternatives = names.stream().sorted(Comparator.comparingInt(String::length).reversed().thenComparing(Comparator.naturalOrder()))
                .map(Pattern::quote).reduce((left, right) -> left + "|" + right).orElse("(?!)");
        return "(?:" + alternatives + ")";
    }

    private List<String> coalesceMechanismComponents(List<String> matches, String selected) {
        JsonNode mechanism = types.get(selected);
        if (mechanism == null || !"mechanism".equals(mechanism.path("kind").asText()) || !matches.contains(selected)) return matches;
        // An explicitly selected mechanism and its registered components describe one assembly.
        // Never absorb an unrelated type, another mechanism, or an unregistered relationship.
        Set<String> components = new HashSet<>();
        for (JsonNode component : mechanism.path("related_types")) components.add(component.asText());
        for (String id : matches) {
            if (id.equals(selected) || components.contains(id)) continue;
            JsonNode candidate = types.get(id);
            boolean correspondingGeneralType = id.endsWith("unspecified") && candidate != null;
            if (correspondingGeneralType) {
                correspondingGeneralType = false;
                for (JsonNode subtype : candidate.path("related_types"))
                    if (components.contains(subtype.asText())) correspondingGeneralType = true;
            }
            if (!correspondingGeneralType) return matches;
        }
        return List.of(selected);
    }

    private List<String> coalesceSamePartNames(String query, List<String> matches, String selected) {
        // A shape description may repeat the general noun for the same specified part.
        // Preserve separate components and every independently specified alternate subtype.
        if (query.matches("(?s).*(?:另一个|另一件|另外|另做|另加|再做|再加|第二个|第二件|多个|各一个|分别|another|additional|second|separate|different|two gears|[两二2](?:个|只|件|种)).*")
                || query.matches("(?s).*(?:和|及|与|以及|and)\\s*(?:一个|一件|一只|one\\b|a\\b|an\\b|another|另|齿轮|gear\\b).*")) return matches;
        List<String> specific = matches.stream().filter(id -> !id.endsWith("unspecified")).toList();
        if (specific.size() != 1 || !selected.isBlank() && !selected.equals(specific.getFirst())) return matches;
        String subtype = specific.getFirst();
        return matches.stream().filter(id -> !id.endsWith("unspecified")
                || !contains(types.get(id).path("related_types"), subtype)).toList();
    }

    private List<String> coalesceQualifiedPairName(String query, List<String> matches, String selected) {
        JsonNode part = types.get(selected);
        JsonNode pair = types.get("gear-pair");
        if (part == null || !"part".equals(part.path("kind").asText()) || pair == null
                || !matches.contains(selected) || !matches.contains("gear-pair")) return matches;
        // A selected part may qualify the same noun as “double-helical gear pair”.
        // Absorb only overlapping names; an independent pair remains another target.
        for (JsonNode alias : pair.path("aliases")) {
            String term = alias.asText().toLowerCase(Locale.ROOT);
            int from = 0;
            int at;
            while ((at = query.indexOf(term, from)) >= 0) {
                from = at + term.length();
                String shared = "齿轮副".equals(term) ? "齿轮" : "gear pair".equals(term) ? "gear" : null;
                if (shared == null) return matches;
                boolean qualified = false;
                for (JsonNode partAlias : part.path("aliases")) {
                    String name = partAlias.asText().toLowerCase(Locale.ROOT);
                    int start = at + shared.length() - name.length();
                    if (name.endsWith(shared) && start >= 0 && query.startsWith(name, start)
                            && (!"gear".equals(shared) || start == 0 || !isLatinLetter(query.charAt(start - 1)))) {
                        qualified = true;
                        break;
                    }
                }
                if (!qualified) return matches;
            }
        }
        return matches.stream().filter(id -> !"gear-pair".equals(id)).toList();
    }

    private static boolean isLatinLetter(char character) { return character >= 'a' && character <= 'z'; }

    private static List<QualifiedGearName> qualifiedGearNames(String query) {
        // Compose local name modifiers instead of adding complete user sentences as aliases.
        // The span cannot cross punctuation or conjunctions into a different component.
        List<QualifiedGearName> names = new ArrayList<>();
        for (Pattern pattern : QUALIFIED_GEAR_NAMES) {
            Matcher matcher = pattern.matcher(query);
            while (matcher.find()) {
                String name = matcher.group();
                boolean internal = name.contains("内") || name.contains("internal");
                boolean external = name.contains("外") || name.contains("external");
                boolean qualified = name.matches("(?s).*(?:渐开线|直齿|斜齿|螺旋|圆柱|环形|锥齿|圆锥|involute|spur|helical|bevel|cylindrical|ring).*");
                if ((!internal && !external) || !qualified) continue;
                boolean straight = name.contains("直齿") || name.contains("spur");
                boolean otherToothForm = name.matches("(?s).*(?:斜齿|螺旋|锥齿|圆锥|helical|bevel).*");
                boolean conflict = internal && (external || !straight || otherToothForm);
                String type = straight && !otherToothForm && !conflict
                        ? internal ? "internal-spur-gear" : "involute-spur-gear" : null;
                if (type != null || conflict)
                    names.add(new QualifiedGearName(matcher.group(), type, matcher.start(), matcher.end(), conflict));
            }
        }
        return names;
    }

    private List<String> candidates(String query) {
        record Hit(String id, String alias, int start, int end) {}
        List<Hit> hits = new ArrayList<>();
        for (Map.Entry<String, JsonNode> entry : types.entrySet()) for (JsonNode alias : entry.getValue().path("aliases")) {
            String term = alias.asText().toLowerCase(Locale.ROOT);
            int from = 0;
            int at;
            while ((at = query.indexOf(term, from)) >= 0) {
                from = at + term.length();
                if ("齿轮".equals(term) && query.startsWith("齿轮箱", at)) continue;
                if (term.matches("[a-z -]+") && (at > 0 && isLatinLetter(query.charAt(at - 1))
                        || at + term.length() < query.length() && isLatinLetter(query.charAt(at + term.length())))) continue;
                hits.add(new Hit(entry.getKey(), term, at, from));
            }
        }
        for (QualifiedGearName name : qualifiedGearNames(query))
            if (name.type() != null) hits.add(new Hit(name.type(), name.name(), name.start(), name.end()));
        // A general “gear” inside a precise alias is not an independent candidate.
        return hits.stream().filter(hit -> hits.stream().noneMatch(other -> !other.id().equals(hit.id()) && other.start() <= hit.start() && other.end() >= hit.end() && other.alias().length() > hit.alias().length()))
                .map(Hit::id).distinct().sorted().toList();
    }

    /** Runs during process-classes even when Maven is invoked with -DskipTests. */
    public static void main(String[] arguments) throws IOException {
        new CadAiKnowledge(new ObjectMapper(), new CadAiProperties());
    }
}
