package com.xfestudio.xfeservermanager.infra.content;

import com.xfestudio.xfeservermanager.infra.http.JsonCodec;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HexFormat;
import java.util.List;
import java.util.Objects;
import javax.imageio.ImageIO;

/** Bounded, content-addressed media. User supplied names never become filesystem paths. */
public final class ContentAssetStore {
    public static final int MAX_ASSET_BYTES = 8 * 1024 * 1024;
    public static final long MAX_TOTAL_BYTES = 64L * 1024 * 1024;
    private final Path directory;
    private final JsonCodec json = new JsonCodec();

    public ContentAssetStore(Path directory) {
        this.directory = directory.toAbsolutePath().normalize();
    }

    public record Asset(String id, String name, String mimeType, long bytes, String resourceLocation) {}

    public synchronized List<Asset> list() throws IOException {
        ensureDirectory(directory);
        var assets = new ArrayList<Asset>();
        try (var entries = Files.list(directory)) {
            for (Path path : entries.filter(p -> p.getFileName().toString().matches("[a-f0-9]{64}\\.json")).sorted().toList()) {
                requireRegular(path);
                try (var input = Files.newInputStream(path)) {
                    Asset asset = json.read(input, Asset.class, Files.size(path), 4096);
                    if (!path.getFileName().toString().equals(asset.id() + ".json")
                            || !asset.resourceLocation().equals("xfesmcontent:uploaded_" + asset.id())
                            || asset.bytes() < 1 || asset.bytes() > MAX_ASSET_BYTES
                            || !List.of("image/png", "audio/ogg").contains(asset.mimeType())) {
                        throw new IOException("Invalid stored content asset metadata");
                    }
                    assets.add(asset);
                    if (assets.size() > 256) throw new IOException("Content asset count exceeds limit");
                }
            }
        }
        return List.copyOf(assets);
    }

    public synchronized Asset upload(String name, String mimeType, String dataBase64) throws IOException {
        String safeName = Objects.toString(name, "").trim();
        if (safeName.isEmpty() || safeName.length() > 128 || safeName.codePoints().anyMatch(Character::isISOControl)) {
            throw new IllegalArgumentException("素材名称必须为 1–128 个可打印字符");
        }
        if (!List.of("image/png", "audio/ogg").contains(mimeType)) {
            throw new IllegalArgumentException("仅支持 PNG 图片和 OGG Vorbis 音频");
        }
        if (dataBase64 == null || dataBase64.length() > ((MAX_ASSET_BYTES + 2L) / 3L) * 4L) {
            throw new IllegalArgumentException("单个素材不能超过 8 MiB");
        }
        byte[] bytes;
        try { bytes = Base64.getDecoder().decode(dataBase64); }
        catch (IllegalArgumentException invalid) { throw new IllegalArgumentException("素材 Base64 编码无效"); }
        if (bytes.length == 0 || bytes.length > MAX_ASSET_BYTES) throw new IllegalArgumentException("素材大小必须为 1 字节至 8 MiB");
        try { validateMedia(mimeType, bytes); }
        catch (IOException invalidMedia) { throw new IllegalArgumentException("素材数据无法解码或已损坏", invalidMedia); }
        String id = sha256(bytes);
        List<Asset> existing = list();
        for (Asset asset : existing) if (asset.id().equals(id)) return asset;
        if (existing.size() >= 256 || existing.stream().mapToLong(Asset::bytes).sum() + bytes.length > MAX_TOTAL_BYTES) {
            throw new IllegalArgumentException("素材库最多 256 项，总大小不超过 64 MiB");
        }
        var asset = new Asset(id, safeName, mimeType, bytes.length, "xfesmcontent:uploaded_" + id);
        atomicWrite(directory.resolve(id + ".bin"), bytes);
        atomicWrite(directory.resolve(id + ".json"), json.writeBytes(asset));
        return asset;
    }

    public byte[] read(Asset asset) throws IOException {
        if (!asset.id().matches("[a-f0-9]{64}")) throw new IllegalArgumentException("Invalid asset id");
        Path path = directory.resolve(asset.id() + ".bin");
        requireRegular(path);
        if (Files.size(path) != asset.bytes() || asset.bytes() > MAX_ASSET_BYTES) throw new IOException("Content asset size mismatch");
        byte[] bytes = Files.readAllBytes(path);
        if (!sha256(bytes).equals(asset.id())) throw new IOException("Content asset digest mismatch");
        return bytes;
    }

    static void validateMedia(String mimeType, byte[] bytes) throws IOException {
        if (mimeType.equals("image/png")) {
            byte[] magic = {(byte)137, 80, 78, 71, 13, 10, 26, 10};
            if (bytes.length < 33 || !java.util.Arrays.equals(magic, java.util.Arrays.copyOf(bytes, 8))) {
                throw new IllegalArgumentException("PNG 文件头无效");
            }
            try (var stream = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes))) {
                var readers = ImageIO.getImageReaders(stream);
                if (!readers.hasNext()) throw new IllegalArgumentException("无法读取 PNG");
                var reader = readers.next();
                try {
                    reader.setInput(stream, true, true);
                    int width = reader.getWidth(0), height = reader.getHeight(0);
                    if (width < 1 || height < 1 || width > 2048 || height > 2048) {
                        throw new IllegalArgumentException("PNG 尺寸不得超过 2048 × 2048");
                    }
                    if (reader.read(0) == null) throw new IllegalArgumentException("PNG 图片数据损坏");
                } finally { reader.dispose(); }
            }
        } else {
            // Validate a single complete Vorbis logical stream. Full sample decoding remains
            // the client's codec responsibility, but malformed containers/headers never publish.
            int offset = 0, page = 0, packetCount = 0, serial = 0;
            boolean continued = false, ended = false;
            var packet = new java.io.ByteArrayOutputStream();
            while (offset < bytes.length) {
                if (bytes.length - offset < 27 || bytes[offset] != 'O' || bytes[offset + 1] != 'g'
                        || bytes[offset + 2] != 'g' || bytes[offset + 3] != 'S' || bytes[offset + 4] != 0) {
                    throw new IllegalArgumentException("OGG 页结构无效");
                }
                int segments = Byte.toUnsignedInt(bytes[offset + 26]);
                if (offset + 27 + segments > bytes.length) throw new IllegalArgumentException("OGG 页被截断");
                int body = offset + 27 + segments, length = 0;
                for (int index = 0; index < segments; index++) length += Byte.toUnsignedInt(bytes[offset + 27 + index]);
                if (body + length > bytes.length || length == 0) throw new IllegalArgumentException("OGG 音频数据被截断");
                int flags = Byte.toUnsignedInt(bytes[offset + 5]);
                int currentSerial = littleInt(bytes, offset + 14);
                if (page == 0) serial = currentSerial;
                if (ended || (flags & ~7) != 0 || ((flags & 2) != 0) != (page == 0)
                        || ((flags & 1) != 0) != continued || serial != currentSerial
                        || littleInt(bytes, offset + 18) != page++) {
                    throw new IllegalArgumentException("OGG 音轨序列或分页标志无效");
                }
                int expectedCrc = littleInt(bytes, offset + 22), crc = 0;
                for (int index = offset; index < body + length; index++) {
                    int value = index >= offset + 22 && index < offset + 26 ? 0 : Byte.toUnsignedInt(bytes[index]);
                    crc ^= value << 24;
                    for (int bit = 0; bit < 8; bit++) crc = (crc << 1) ^ ((crc & 0x80000000) != 0 ? 0x04c11db7 : 0);
                }
                if (crc != expectedCrc) throw new IllegalArgumentException("OGG 校验和不匹配，音频可能已损坏");
                int cursor = body;
                for (int index = 0; index < segments; index++) {
                    int part = Byte.toUnsignedInt(bytes[offset + 27 + index]);
                    packet.write(bytes, cursor, part); cursor += part;
                    continued = part == 255;
                    if (!continued) {
                        byte[] complete = packet.toByteArray();
                        if (packetCount < 3) validateVorbisHeader(packetCount, complete);
                        else if (complete.length == 0 || (complete[0] & 1) != 0) throw new IllegalArgumentException("OGG 音频包无效");
                        packetCount++; packet.reset();
                    }
                }
                ended = (flags & 4) != 0;
                offset = body + length;
            }
            if (!ended || continued || packetCount < 4) throw new IllegalArgumentException("OGG 音频不完整");
        }
    }

    private static void validateVorbisHeader(int index, byte[] packet) {
        if (packet.length < 8 || packet[0] != new int[] {1, 3, 5}[index]
                || !new String(packet, 1, 6, java.nio.charset.StandardCharsets.US_ASCII).equals("vorbis")) {
            throw new IllegalArgumentException("缺少有效的 Vorbis 识别/注释/设置头");
        }
        if (index == 0) {
            if (packet.length != 30 || littleInt(packet, 7) != 0 || packet[29] != 1) throw new IllegalArgumentException("Vorbis 识别头无效");
            int channels = Byte.toUnsignedInt(packet[11]), sampleRate = littleInt(packet, 12);
            int small = packet[28] & 15, large = (packet[28] & 255) >>> 4;
            if (channels < 1 || channels > 2 || sampleRate < 8000 || sampleRate > 96000
                    || small < 6 || large > 13 || small > large) throw new IllegalArgumentException("仅支持单/双声道 8–96 kHz 的 Vorbis 音频");
        } else if (index == 1) {
            int cursor = skipVorbisString(packet, 7);
            if (cursor + 4 > packet.length) throw new IllegalArgumentException("Vorbis 注释头被截断");
            int count = littleInt(packet, cursor); cursor += 4;
            if (count < 0 || count > 4096) throw new IllegalArgumentException("Vorbis 注释数量超过安全上限");
            for (int comment = 0; comment < count; comment++) cursor = skipVorbisString(packet, cursor);
            if (cursor + 1 != packet.length || packet[cursor] != 1) throw new IllegalArgumentException("Vorbis 注释结束标记无效");
        } else if (packet.length < 64) { throw new IllegalArgumentException("Vorbis 设置头不完整"); }
    }

    private static int skipVorbisString(byte[] packet, int cursor) {
        if (cursor + 4 > packet.length) throw new IllegalArgumentException("Vorbis 文本被截断");
        int size = littleInt(packet, cursor);
        if (size < 0 || size > packet.length - cursor - 4) throw new IllegalArgumentException("Vorbis 文本长度无效");
        return cursor + 4 + size;
    }

    private static int littleInt(byte[] bytes, int offset) { return ByteBuffer.wrap(bytes, offset, 4).order(ByteOrder.LITTLE_ENDIAN).getInt(); }

    public static String sha256(byte[]... values) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            for (byte[] value : values) digest.update(value);
            return HexFormat.of().formatHex(digest.digest());
        } catch (NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); }
    }

    public static void atomicWrite(Path destination, byte[] bytes) throws IOException {
        ensureDirectory(destination.toAbsolutePath().normalize().getParent());
        if (Files.isSymbolicLink(destination)) throw new IOException("Symbolic links are not accepted for content files");
        Path temporary = Files.createTempFile(destination.getParent(), ".content-", ".tmp");
        try {
            Files.write(temporary, bytes);
            try (var channel = java.nio.channels.FileChannel.open(temporary, java.nio.file.StandardOpenOption.WRITE)) { channel.force(true); }
            Files.move(temporary, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
        } finally { Files.deleteIfExists(temporary); }
    }

    static void ensureDirectory(Path directory) throws IOException {
        Path absolute = directory.toAbsolutePath().normalize();
        for (Path current = absolute; current != null; current = current.getParent()) {
            if (Files.isSymbolicLink(current)) throw new IOException("Symbolic links are not accepted for content directories");
        }
        Files.createDirectories(absolute);
    }

    static void requireRegular(Path file) throws IOException {
        ensureDirectory(file.toAbsolutePath().normalize().getParent());
        if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Content file is missing or not regular");
    }
}
