package com.xfestudio.xfeservermanager.infra.content;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.xfestudio.xfeservermanager.core.content.ContentDefinition;
import com.xfestudio.xfeservermanager.core.content.ContentWorkspace;
import com.xfestudio.xfeservermanager.infra.http.JsonCodec;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HashSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.CRC32;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/** Bounded, declarative-only transfer. A download never changes a running registry/resource pack. */
public final class ContentUpdateBundle {
    public static final String PROTOCOL = "xfesm-content-v1";
    public static final int CHUNK_BYTES = 16_384;
    public static final int MAX_MANIFEST_BYTES = 2 * 1024 * 1024;
    public static final int MAX_RESOURCE_BYTES = 72 * 1024 * 1024;
    public static final int MAX_BYTES = MAX_MANIFEST_BYTES + MAX_RESOURCE_BYTES + 4;
    private static final JsonCodec JSON = new JsonCodec();

    private ContentUpdateBundle() { }

    public record Descriptor(String protocol, String kind, boolean enabled, long revision, String fingerprint,
                             long bytes, int chunkBytes, int chunks, String sha256,
                             String minecraftVersion, String modVersion) {
        public Descriptor {
            if (!PROTOCOL.equals(protocol) || !"descriptor".equals(kind) || !enabled
                    || revision < 0 || revision >= 9_007_199_254_740_991L
                    || !hash(fingerprint) || !hash(sha256) || bytes < 5 || bytes > MAX_BYTES
                    || chunkBytes != CHUNK_BYTES || chunks != (bytes + CHUNK_BYTES - 1) / CHUNK_BYTES
                    || minecraftVersion == null || !minecraftVersion.matches("[0-9.]{3,24}")
                    || modVersion == null || !modVersion.matches("[A-Za-z0-9_.+\\-]{1,64}")) {
                throw new IllegalArgumentException("内容更新描述符无效或超过安全上限");
            }
        }
    }

    /** Bytes are private and never exposed except as a bounded defensive chunk copy. */
    public static final class Snapshot {
        private final Descriptor descriptor;
        private final byte[] bytes;
        private Snapshot(Descriptor descriptor, byte[] bytes) { this.descriptor = descriptor; this.bytes = bytes; }
        public Descriptor descriptor() { return descriptor; }
        public byte[] chunk(int index) {
            if (index < 0 || index >= descriptor.chunks()) throw new IllegalArgumentException("内容分块索引无效");
            int start = index * CHUNK_BYTES;
            return Arrays.copyOfRange(bytes, start, Math.min(bytes.length, start + CHUNK_BYTES));
        }
    }

    public record StagedUpdate(Descriptor descriptor, Path bundle) { }
    private record Decoded(ContentWorkspace workspace, byte[] manifest, byte[] resources) { }

    /** Called once at startup, not from a status request or a server tick. */
    public static Snapshot capture(Path directory, String expectedFingerprint, String minecraft, String mod) throws IOException {
        Path manifestFile = directory.resolve("pack.json");
        if (!Files.exists(manifestFile)) return null;
        byte[] manifest = read(manifestFile, MAX_MANIFEST_BYTES);
        ContentWorkspace workspace = manifest(manifest);
        if (!workspace.enabled()) return null;
        if (!workspace.updatedBy().equals("content-publisher")) {
            throw new IOException("旧安装包含内部发布者字段，请重新发布并重启后启用公开自动下载");
        }
        byte[] resources = read(resources(directory, workspace.revision()), MAX_RESOURCE_BYTES);
        String fingerprint = ContentAssetStore.sha256(manifest, resources);
        if (!fingerprint.equals(expectedFingerprint)) throw new IOException("待分发内容不是本次启动已加载的版本");
        byte[] wire = ByteBuffer.allocate(4 + manifest.length + resources.length).putInt(manifest.length).put(manifest).put(resources).array();
        return new Snapshot(new Descriptor(PROTOCOL, "descriptor", true, workspace.revision(), fingerprint,
                wire.length, CHUNK_BYTES, (wire.length + CHUNK_BYTES - 1) / CHUNK_BYTES,
                ContentAssetStore.sha256(wire), minecraft, mod), wire);
    }

    public static Descriptor readDescriptor(String text, String expectedMinecraft, String expectedMod) throws IOException {
        if (text == null || text.length() > 4096) throw new IOException("内容更新描述符过大");
        try {
            JsonObject object = strictObject(text.getBytes(StandardCharsets.UTF_8));
            for (String key : List.of("revision", "bytes", "chunkBytes", "chunks")) integer(object, key);
            if (!object.getAsJsonPrimitive("enabled").isBoolean()) throw new IllegalArgumentException("enabled");
            Descriptor result = JSON.read(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)), Descriptor.class, -1, 16_384);
            if (!result.minecraftVersion().equals(expectedMinecraft) || !result.modVersion().equals(expectedMod)) {
                throw new IOException("服务器 Minecraft / 模组版本不匹配；内容更新不会下载或执行模组 JAR");
            }
            return result;
        } catch (RuntimeException failure) { throw new IOException("内容更新描述符无效", failure); }
    }

    /** A fixed bounded filename; never use a server supplied filesystem path. */
    public static Path downloadTarget(Path directory, Descriptor descriptor) throws IOException {
        Path updates = directory.toAbsolutePath().normalize().resolve("updates");
        ContentAssetStore.ensureDirectory(updates);
        Path target = updates.resolve("download.part");
        if (Files.isSymbolicLink(target) || Files.isDirectory(target)) throw new IOException("下载路径不是普通文件");
        return target;
    }

    public static synchronized StagedUpdate stage(Path directory, Descriptor descriptor, Path download) throws IOException {
        byte[] bytes = read(download, MAX_BYTES);
        Decoded decoded = decode(descriptor, bytes);
        requireCompatible(directory, decoded.workspace());
        requireResourceSlot(directory, decoded);
        Path staged = directory.toAbsolutePath().normalize().resolve("updates/staged.bundle");
        Path pending = staged.resolveSibling("pending.json");
        if (Files.exists(pending)) {
            Descriptor previous = readDescriptor(utf8(read(pending, 16_384)), descriptor.minecraftVersion(), descriptor.modVersion());
            if (!previous.equals(descriptor)) {
                throw new IOException("已有内容更新等待下次启动安装；请先完成该更新，不能覆盖其暂存文件");
            }
        }
        ContentAssetStore.atomicWrite(staged, bytes);
        ContentAssetStore.atomicWrite(staged.resolveSibling("staged.json"), JSON.writeBytes(descriptor));
        return new StagedUpdate(descriptor, staged);
    }

    /** Safe while the game runs: only marks a verified staged bundle for the next client startup. */
    public static synchronized void schedule(Path directory, StagedUpdate staged) throws IOException {
        Path expected = directory.toAbsolutePath().normalize().resolve("updates/staged.bundle");
        if (!expected.equals(staged.bundle().toAbsolutePath().normalize())) throw new IOException("无效的内容暂存位置");
        Decoded decoded = decode(staged.descriptor(), read(expected, MAX_BYTES));
        requireCompatible(directory, decoded.workspace());
        requireResourceSlot(directory, decoded);
        byte[] pending = JSON.writeBytes(staged.descriptor());
        ContentAssetStore.atomicWrite(expected.resolveSibling("pending.json"), pending);
        Descriptor descriptor = staged.descriptor();
        String target = "revision=" + descriptor.revision() + "\nfingerprint=" + descriptor.fingerprint()
                + "\nbytes=" + descriptor.bytes() + "\nsha256=" + descriptor.sha256()
                + "\npendingSha256=" + ContentAssetStore.sha256(pending) + "\n";
        ContentAssetStore.atomicWrite(expected.resolveSibling("restart-target.properties"), target.getBytes(StandardCharsets.UTF_8));
    }

    /** Client-only, BEFORE DeferredRegister suppliers and before opening any world or mounting ZIPs. */
    public static synchronized boolean activatePending(Path directory) throws IOException {
        Path pending = directory.resolve("updates/pending.json");
        if (!Files.exists(pending)) return false;
        byte[] descriptorBytes = read(pending, 16_384);
        JsonObject metadata = strictObject(descriptorBytes);
        Descriptor descriptor;
        try {
            descriptor = readDescriptor(utf8(descriptorBytes), metadata.get("minecraftVersion").getAsString(), metadata.get("modVersion").getAsString());
        } catch (RuntimeException invalid) { throw new IOException("内容更新描述符无效", invalid); }
        Decoded decoded = decode(descriptor, read(directory.resolve("updates/staged.bundle"), MAX_BYTES));
        requireCompatible(directory, decoded.workspace());
        Path current = directory.resolve("pack.json");
        if (Files.exists(current) && installedFingerprint(directory).equals(descriptor.fingerprint())) {
            // A crash after committing pack.json but before consuming pending.json must not replace
            // the previous-version backup with the just-installed version.
            markEnabled(directory);
            Files.delete(pending);
            return true;
        }
        Path resource = resources(directory, decoded.workspace().revision());
        requireResourceSlot(directory, decoded);
        if (Files.exists(current)) {
            byte[] previous = read(current, MAX_MANIFEST_BYTES);
            ContentWorkspace previousWorkspace = manifest(previous);
            byte[] previousResources = read(resources(directory, previousWorkspace.revision()), MAX_RESOURCE_BYTES);
            ContentAssetStore.atomicWrite(directory.resolve("updates/previous-resources.zip"), previousResources);
            ContentAssetStore.atomicWrite(directory.resolve("updates/previous-pack.json"), previous);
        }
        ContentAssetStore.atomicWrite(resource, decoded.resources());
        ContentAssetStore.atomicWrite(resource.resolveSibling("pack.json"), decoded.manifest());
        ContentAssetStore.atomicWrite(current, decoded.manifest());
        // Write the marker after the manifest. A first-install crash must not leave a marker with
        // no manifest, which would otherwise prevent a valid pending transaction from recovering.
        markEnabled(directory);
        Files.delete(pending); // only the one validated, consumed request; no recursive cleanup
        return true;
    }

    public static boolean activatePending(Path directory, String minecraft, String mod) throws IOException {
        Path pending = directory.resolve("updates/pending.json");
        if (!Files.exists(pending)) return false;
        readDescriptor(utf8(read(pending, 16_384)), minecraft, mod);
        return activatePending(directory);
    }

    public static String installedFingerprint(Path directory) throws IOException {
        Path file = directory.resolve("pack.json");
        if (!Files.exists(file)) {
            if (Files.exists(directory.resolve("enabled.marker"))) throw new IOException("已启用的内容清单缺失，请先恢复完整内容包");
            return "";
        }
        byte[] bytes = read(file, MAX_MANIFEST_BYTES);
        ContentWorkspace workspace = manifest(bytes);
        return ContentAssetStore.sha256(bytes, read(resources(directory, workspace.revision()), MAX_RESOURCE_BYTES));
    }

    private static Decoded decode(Descriptor descriptor, byte[] wire) throws IOException {
        if (wire.length != descriptor.bytes() || !ContentAssetStore.sha256(wire).equals(descriptor.sha256())) {
            throw new IOException("内容下载长度或 SHA-256 校验失败，未修改已安装内容");
        }
        int length = ByteBuffer.wrap(wire).getInt();
        if (length < 2 || length > MAX_MANIFEST_BYTES || length >= wire.length - 4) throw new IOException("内容清单长度无效");
        byte[] manifest = Arrays.copyOfRange(wire, 4, 4 + length);
        byte[] resources = Arrays.copyOfRange(wire, 4 + length, wire.length);
        if (resources.length > MAX_RESOURCE_BYTES || !ContentAssetStore.sha256(manifest, resources).equals(descriptor.fingerprint())) {
            throw new IOException("内容注册指纹不匹配");
        }
        ContentWorkspace workspace = manifest(manifest);
        if (!workspace.enabled() || workspace.revision() != descriptor.revision()) throw new IOException("内容清单与描述符不一致");
        validateResources(resources);
        return new Decoded(workspace, manifest, resources);
    }

    private static ContentWorkspace manifest(byte[] bytes) throws IOException {
        try {
            JsonObject object = strictObject(bytes);
            integer(object, "schemaVersion"); integer(object, "revision");
            if (!object.getAsJsonPrimitive("enabled").isBoolean()) throw new IllegalArgumentException("enabled");
            return JSON.read(new ByteArrayInputStream(bytes), ContentWorkspace.class, bytes.length, MAX_MANIFEST_BYTES);
        } catch (RuntimeException failure) { throw new IOException("内容清单格式或属性无效", failure); }
    }

    private static void integer(JsonObject object, String key) {
        if (!object.getAsJsonPrimitive(key).isNumber()) throw new IllegalArgumentException(key);
        object.get(key).getAsBigDecimal().longValueExact();
    }

    private static void requireCompatible(Path directory, ContentWorkspace next) throws IOException {
        Path previousFile = directory.resolve("pack.json");
        if (!Files.exists(previousFile)) {
            if (Files.exists(directory.resolve("enabled.marker"))) throw new IOException("已安装清单缺失，请先恢复");
            return;
        }
        ContentWorkspace previous = manifest(read(previousFile, MAX_MANIFEST_BYTES));
        for (ContentDefinition old : previous.definitions()) {
            var retained = next.definitions().stream().filter(value -> value.id().equals(old.id())).findFirst().orElse(null);
            if (retained == null || retained.kind() != old.kind() || !retained.archetype().equals(old.archetype())) {
                throw new IOException("新包移除或改变了已安装注册项 " + old.id() + "；请为不同内容的服务器使用独立游戏实例，以保护本地世界");
            }
        }
    }

    private static void validateResources(byte[] bytes) throws IOException {
        Map<String, ArchiveEntry> localEntries = new HashMap<>();
        long total = 0;
        int media = 0;
        try (var zip = new ZipInputStream(new ByteArrayInputStream(bytes), StandardCharsets.UTF_8)) {
            java.util.zip.ZipEntry entry;
            while ((entry = zip.getNextEntry()) != null) {
                checkInterrupted();
                String path = entry.getName();
                if (entry.isDirectory() || !allowedResource(path) || localEntries.containsKey(path) || localEntries.size() >= 4096) {
                    throw new IOException("内容资源包含重复、可执行或不允许的路径");
                }
                int limit = path.endsWith(".png") || path.endsWith(".ogg") ? ContentAssetStore.MAX_ASSET_BYTES : MAX_MANIFEST_BYTES;
                if ((path.endsWith(".png") || path.endsWith(".ogg")) && ++media > 256) throw new IOException("内容媒体数量超过 256 项安全上限");
                byte[] content = zip.readNBytes(limit + 1);
                total += content.length;
                if (content.length > limit || total > MAX_RESOURCE_BYTES) throw new IOException("解压内容超过安全预算");
                if (path.endsWith(".png")) ContentAssetStore.validateMedia("image/png", content);
                else if (path.endsWith(".ogg")) ContentAssetStore.validateMedia("audio/ogg", content);
                else strictObject(content);
                var crc = new CRC32(); crc.update(content);
                localEntries.put(path, new ArchiveEntry(content.length, crc.getValue(), ContentAssetStore.sha256(content)));
                zip.closeEntry();
            }
        } catch (RuntimeException failure) { throw new IOException("内容资源格式无效", failure); }
        if (!localEntries.containsKey("pack.mcmeta")) throw new IOException("内容资源缺少 pack.mcmeta");
        requireBoundedCentralDirectory(bytes, localEntries.size());
        // Minecraft mounts ZIPs using their central directory, not ZipInputStream's local headers.
        // Validate both views: otherwise a harmless local name can conceal an executable datapack
        // path or different bytes in the central directory. No archive content is ever extracted.
        Path temporary = Files.createTempFile("xfesm-content-verify-", ".zip");
        try {
            Files.write(temporary, bytes);
            try (var zip = new ZipFile(temporary.toFile(), StandardCharsets.UTF_8)) {
                var centralNames = new HashSet<String>();
                var entries = zip.entries();
                long centralTotal = 0;
                while (entries.hasMoreElements()) {
                    checkInterrupted();
                    var entry = entries.nextElement();
                    String path = entry.getName();
                    ArchiveEntry local = localEntries.get(path);
                    if (entry.isDirectory() || !allowedResource(path) || !centralNames.add(path)
                            || centralNames.size() > 4096 || local == null) throw new IOException("资源中央目录包含不一致或不允许的路径");
                    if (entry.getSize() != local.size() || entry.getCrc() != local.crc()
                            || entry.getCompressedSize() < 0 || entry.getCompressedSize() > bytes.length) throw new IOException("资源中央目录长度或校验和不一致");
                    byte[] content;
                    try (var input = zip.getInputStream(entry)) { content = input.readNBytes(local.size() + 1); }
                    centralTotal += content.length;
                    if (centralTotal > MAX_RESOURCE_BYTES || content.length != local.size()
                            || !ContentAssetStore.sha256(content).equals(local.sha256())) throw new IOException("资源中央目录内容与已验证数据不一致");
                }
                if (!centralNames.equals(localEntries.keySet())) throw new IOException("资源中央目录缺少已验证条目");
            }
        } finally { Files.deleteIfExists(temporary); }
    }

    private record ArchiveEntry(int size, long crc, String sha256) { }

    private static void requireBoundedCentralDirectory(byte[] bytes, int entries) throws IOException {
        // ZipFile allocates its index while opening, before callers can enumerate entries. Do not
        // let an untrusted ZIP64/EOCD entry count request an unbounded allocation in the JDK.
        var view = ByteBuffer.wrap(bytes).order(java.nio.ByteOrder.LITTLE_ENDIAN);
        int end = -1;
        for (int i = bytes.length - 22; i >= Math.max(0, bytes.length - 65_557); i--) {
            if (view.getInt(i) == 0x06054b50 && i + 22 + Short.toUnsignedInt(view.getShort(i + 20)) == bytes.length) { end = i; break; }
        }
        if (end < 0 || view.getShort(end + 4) != 0 || view.getShort(end + 6) != 0
                || Short.toUnsignedInt(view.getShort(end + 8)) != entries
                || Short.toUnsignedInt(view.getShort(end + 10)) != entries) throw new IOException("资源中央目录数量或分卷格式无效");
        long length = Integer.toUnsignedLong(view.getInt(end + 12));
        long offset = Integer.toUnsignedLong(view.getInt(end + 16));
        if (offset + length != end || offset > end) throw new IOException("资源中央目录范围无效；不接受 ZIP64");
        int cursor = (int) offset, seen = 0;
        while (cursor < end) {
            if (cursor + 46 > end || view.getInt(cursor) != 0x02014b50 || ++seen > entries) throw new IOException("资源中央目录结构无效");
            int name = Short.toUnsignedInt(view.getShort(cursor + 28));
            int extra = Short.toUnsignedInt(view.getShort(cursor + 30));
            int comment = Short.toUnsignedInt(view.getShort(cursor + 32));
            if (name < 1 || name > 256 || view.getShort(cursor + 34) != 0
                    || Integer.toUnsignedLong(view.getInt(cursor + 42)) >= offset) throw new IOException("资源中央目录条目无效");
            cursor += 46 + name + extra + comment;
        }
        if (cursor != end || seen != entries) throw new IOException("资源中央目录条目数量不一致");
    }

    private static void markEnabled(Path directory) throws IOException {
        ContentAssetStore.atomicWrite(directory.resolve("enabled.marker"),
                "Custom content is enabled. Restore the matching pack before opening worlds.\n".getBytes(StandardCharsets.UTF_8));
    }

    private static void requireResourceSlot(Path directory, Decoded decoded) throws IOException {
        Path resource = resources(directory, decoded.workspace().revision());
        if (Files.exists(resource) && !Arrays.equals(read(resource, MAX_RESOURCE_BYTES), decoded.resources())) {
            throw new IOException("相同修订号对应不同资源；不能覆盖已安装版本，请为不同服务器使用独立游戏实例");
        }
    }

    private static void checkInterrupted() throws IOException {
        if (Thread.currentThread().isInterrupted()) throw new IOException("内容校验已取消");
    }

    private static String utf8(byte[] bytes) throws IOException {
        return StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
                .onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(bytes)).toString();
    }

    private static JsonObject strictObject(byte[] bytes) throws IOException {
        String text = utf8(bytes);
        // Gson 2.10 (bundled with MC 1.20.1) predates Strictness. Its legacy strict mode
        // tolerates a few non-JSON escapes/control characters, so screen them explicitly.
        boolean quoted = false;
        for (int i = 0; i < text.length(); i++) {
            char value = text.charAt(i);
            if (value == '"') { quoted = !quoted; continue; }
            if (quoted) {
                if (value < 0x20) throw new IOException("JSON 字符串包含未转义控制字符");
                if (value == '\\') {
                    if (++i == text.length() || "\"\\/bfnrtu".indexOf(text.charAt(i)) < 0) throw new IOException("JSON 转义无效");
                }
            } else if ("{}[]:, \t\r\n0123456789.+-eEtrufalsn".indexOf(value) < 0) {
                throw new IOException("内容必须使用严格 JSON 格式");
            }
        }
        try (var reader = new JsonReader(new StringReader(text))) {
            reader.setLenient(false);
            // This public method is only present in Gson 2.11+. Keep binary compatibility
            // with the older Minecraft runtime while using STRICT where available.
            try {
                Class<?> mode = Class.forName("com.google.gson.Strictness");
                JsonReader.class.getMethod("setStrictness", mode).invoke(reader, mode.getField("STRICT").get(null));
            } catch (ClassNotFoundException | NoSuchMethodException olderGson) {
                // The legacy reader plus lexical checks above enforce the same input subset.
            } catch (ReflectiveOperationException invalidRuntime) { throw new IOException("无法启用严格 JSON 校验", invalidRuntime); }
            JsonElement result = readJson(reader, 0, new int[] {200_000});
            if (reader.peek() != JsonToken.END_DOCUMENT || !result.isJsonObject()) throw new IOException("资源 JSON 必须是单个对象");
            return result.getAsJsonObject();
        } catch (RuntimeException invalid) { throw new IOException("内容 JSON 格式无效", invalid); }
    }

    private static JsonElement readJson(JsonReader reader, int depth, int[] remaining) throws IOException {
        checkInterrupted();
        if (depth > 64 || --remaining[0] < 0) throw new IOException("JSON 嵌套或节点数量超过安全上限");
        return switch (reader.peek()) {
            case BEGIN_OBJECT -> {
                reader.beginObject();
                var object = new JsonObject();
                while (reader.hasNext()) {
                    String name = reader.nextName();
                    if (object.has(name)) throw new IOException("JSON 包含重复字段");
                    object.add(name, readJson(reader, depth + 1, remaining));
                }
                reader.endObject(); yield object;
            }
            case BEGIN_ARRAY -> {
                reader.beginArray();
                var array = new JsonArray();
                while (reader.hasNext()) array.add(readJson(reader, depth + 1, remaining));
                reader.endArray(); yield array;
            }
            case STRING -> new JsonPrimitive(reader.nextString());
            case NUMBER -> {
                String number = reader.nextString();
                if (number.length() > 128) throw new IOException("JSON 数值长度超过安全上限");
                yield new JsonPrimitive(new BigDecimal(number));
            }
            case BOOLEAN -> new JsonPrimitive(reader.nextBoolean());
            case NULL -> { reader.nextNull(); yield JsonNull.INSTANCE; }
            default -> throw new IOException("内容 JSON 结构无效");
        };
    }

    private static boolean allowedResource(String path) {
        if (path == null || path.length() > 256 || path.contains("..") || path.contains("\\") || path.startsWith("/")) return false;
        if (path.equals("pack.mcmeta")) return true;
        if (path.matches("assets/xfesmcontent/(textures/[a-z0-9_/-]+\\.png|sounds/[a-z0-9_/-]+\\.ogg)")) return true;
        if (path.matches("assets/xfesmcontent/((models|blockstates|items|lang)/[a-z0-9_/-]+\\.json|sounds\\.json)")) return true;
        if (path.matches("data/xfesmcontent/(loot_tables|loot_table)/(blocks|entities)/[a-z0-9_]+\\.json")) return true;
        return path.matches("data/minecraft/tags/(blocks|block)/(mineable/pickaxe|needs_iron_tool)\\.json");
    }

    private static Path resources(Path directory, long revision) { return directory.resolve("releases").resolve(Long.toString(revision)).resolve("resources.zip"); }
    private static byte[] read(Path file, int limit) throws IOException {
        ContentAssetStore.requireRegular(file);
        if (Files.size(file) > limit) throw new IOException("内容文件超过安全上限");
        try (var input = Files.newInputStream(file)) {
            byte[] bytes = input.readNBytes(limit + 1);
            if (bytes.length > limit) throw new IOException("内容文件超过安全上限");
            return bytes;
        }
    }
    private static boolean hash(String value) { return value != null && value.matches("[a-f0-9]{64}"); }
}
