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

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.service.config.CadAiProperties;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;

/** Preserves the published v2 routing expectations, separately from the live utility policy. */
final class HistoricalCadAiKnowledge {
    private static final Set<String> RETIRED_BUILD_GATE_CASES = Set.of(
            "unavailable-01", "compatibility-involute-spur-gear", "compatibility-internal-spur-gear",
            "compatibility-helical-cylindrical-gear", "compatibility-straight-rack", "compatibility-helical-rack",
            "compatibility-worm", "compatibility-straight-bevel-gear", "compatibility-spiral-bevel-gear",
            "compatibility-worm-wheel", "compatibility-gear-pair", "compatibility-rack-and-pinion",
            "compatibility-worm-drive", "compatibility-planetary-gear-mechanism", "mounting-plate-exact-build-only",
            "stepped-shaft-exact-build-only", "hex-head-bolt-exact-build-only", "ribbed-bearing-housing-exact-build-only",
            "covered-thin-wall-enclosure-exact-build-only", "herringbone-gear-exact-build-only", "double-helical-gear-exact-build-only");
    private HistoricalCadAiKnowledge() {}

    static String runtimeStatus(JsonNode item) {
        String recorded = item.path("status").asText();
        // Preserve the historical JSON byte-for-byte while explicitly testing the sole
        // intentional behaviour change: these complete requests no longer gate on build.
        if (!"incompatible".equals(recorded)) return recorded;
        if (!RETIRED_BUILD_GATE_CASES.contains(item.path("id").asText()))
            throw new AssertionError("Undeclared historical build-gate expectation: " + item.path("id").asText());
        return "matched";
    }

    static JsonNode policy(ObjectMapper json) throws IOException {
        try (InputStream input = HistoricalCadAiKnowledge.class.getResourceAsStream(
                "/cad/ai/knowledge/evals/policy-before-utility-pruning-v1.json")) {
            if (input == null) throw new IOException("Missing historical CAD policy");
            byte[] bytes = input.readAllBytes();
            CadAiKnowledge.verifyHash(bytes, "773fa40bdd5daf51282037d6e46c9afce2dcf5820f2baff24a4db63bc186ee80");
            return json.readTree(bytes);
        }
    }

    static CadAiKnowledge knowledge(ObjectMapper json, CadAiProperties properties) throws IOException {
        return new CadAiKnowledge(json, properties, policy(json));
    }

    static CadAiTools tools(ObjectMapper json) throws IOException {
        return new CadAiTools(json, policy(json));
    }
}
