import { profileCardLayoutFromMetadata } from "@/features/resources/profileCardLayout.js";
import { mp4AlphaLayoutFromMetadata, mp4AlphaLayoutKey } from "@/features/resources/mp4AlphaLayout.js";

export const emptyResourceMetadata = "{}";
const roomNameColorPattern = /^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/;
export const roomBorderFormatOptions = ["png", "jpeg", "webp", "gif", "svga", "pag", "mp4"];

export function resourceRequiresExplicitVisualFormat(resourceType) {
    return resourceType === "mic_seat_animation" || resourceType === "room_border";
}

export function resourceMetadataJSON(resourceType, metadataJson) {
    const metadata = {};
    const profileCardLayout = resourceType === "profile_card" ? profileCardLayoutFromMetadata(metadataJson) : null;
    if (profileCardLayout) {
        metadata.profile_card_layout = profileCardLayout;
    }
    const mp4AlphaLayout = mp4AlphaLayoutFromMetadata(metadataJson);
    if (mp4AlphaLayout) {
        metadata.animation_format = "mp4";
        metadata[mp4AlphaLayoutKey] = mp4AlphaLayout;
    }
    if (resourceRequiresExplicitVisualFormat(resourceType)) {
        const format = roomBorderFormatFromMetadata(metadataJson);
        if (format) {
            metadata.format = format;
        }
    }
    if (resourceType === "room_name_style") {
        const style = roomNameStyleFromMetadata(metadataJson);
        if (style) {
            metadata.text_colors = style.textColors;
            if (style.stops.length) {
                metadata.stops = style.stops;
            }
            if (style.angleDegrees !== null) {
                metadata.angle_degrees = style.angleDegrees;
            }
        }
    }
    return Object.keys(metadata).length ? JSON.stringify(metadata) : emptyResourceMetadata;
}

// 麦位动效和房间边框的格式跟资源记录一起保存，客户端不需要从 CDN URL 后缀猜渲染器。
export function roomBorderFormatMetadataJSON(metadataJson, value) {
    const metadata = parseMetadataObject(metadataJson);
    const format = String(value || "")
        .trim()
        .toLowerCase();
    if (roomBorderFormatOptions.includes(format)) {
        metadata.format = format;
    } else {
        delete metadata.format;
    }
    return stringifyMetadata(metadata);
}

export function roomBorderFormatFromMetadata(metadataJson) {
    const metadata = parseMetadataObject(metadataJson);
    const format = String(metadata.format || metadata.animation_format || "")
        .trim()
        .toLowerCase();
    return roomBorderFormatOptions.includes(format) ? format : "";
}

// 房名颜色属于资源目录事实。后台把结构化输入归一成 room-service 唯一读取的 snake_case，
// Flutter 只消费房间快照，不能再按 VIP 等级维护另一份渐变配置。
export function roomNameStyleMetadataJSON(metadataJson, input) {
    const style = parseRoomNameStyleInput(input);
    if (!style) {
        return emptyResourceMetadata;
    }
    const metadata = parseMetadataObject(metadataJson);
    delete metadata.textColors;
    delete metadata.angleDegrees;
    metadata.text_colors = style.textColors;
    if (style.stops.length) {
        metadata.stops = style.stops;
    } else {
        delete metadata.stops;
    }
    if (style.angleDegrees !== null) {
        metadata.angle_degrees = style.angleDegrees;
    } else {
        delete metadata.angle_degrees;
    }
    return stringifyMetadata(metadata);
}

export function roomNameStyleFromMetadata(metadataJson) {
    const metadata = parseMetadataObject(metadataJson);
    const textColors = Array.isArray(metadata.text_colors)
        ? metadata.text_colors.map((value) => String(value).trim()).filter(Boolean)
        : Array.isArray(metadata.textColors)
          ? metadata.textColors.map((value) => String(value).trim()).filter(Boolean)
          : [];
    const stops = Array.isArray(metadata.stops) ? metadata.stops.map(Number) : [];
    const rawAngle = metadata.angle_degrees ?? metadata.angleDegrees;
    const angleDegrees = rawAngle === undefined || rawAngle === null || rawAngle === "" ? null : Number(rawAngle);
    const style = { angleDegrees, stops, textColors };
    return validateRoomNameStyle(style) ? null : style;
}

export function roomNameStyleFormFromMetadata(metadataJson) {
    const style = roomNameStyleFromMetadata(metadataJson);
    return {
        roomNameAngleDegrees:
            style?.angleDegrees === null || style?.angleDegrees === undefined ? "" : String(style.angleDegrees),
        roomNameStops: style?.stops?.join(", ") || "",
        roomNameTextColors: style?.textColors?.join(", ") || "",
    };
}

export function parseRoomNameStyleInput(input) {
    const textColors = splitRoomNameStyleValues(input?.roomNameTextColors);
    const stopTokens = splitRoomNameStyleValues(input?.roomNameStops);
    const stops = stopTokens.map(Number);
    const rawAngle = String(input?.roomNameAngleDegrees ?? "").trim();
    const angleDegrees = rawAngle === "" ? null : Number(rawAngle);
    const style = { angleDegrees, stops, textColors };
    return validateRoomNameStyle(style) ? null : style;
}

export function roomNameStyleInputError(input) {
    const textColors = splitRoomNameStyleValues(input?.roomNameTextColors);
    if (!textColors.length || textColors.length > 8 || textColors.some((color) => !roomNameColorPattern.test(color))) {
        return "请输入 1 至 8 个 #RRGGBB 或 #RRGGBBAA 颜色";
    }
    const stopTokens = splitRoomNameStyleValues(input?.roomNameStops);
    if (stopTokens.length) {
        const stops = stopTokens.map(Number);
        if (
            stops.length !== textColors.length ||
            stops.some((stop) => !Number.isFinite(stop) || stop < 0 || stop > 1) ||
            stops.some((stop, index) => index > 0 && stop < stops[index - 1])
        ) {
            return "渐变位置必须与颜色数量一致，并按 0 至 1 递增";
        }
    }
    const rawAngle = String(input?.roomNameAngleDegrees ?? "").trim();
    if (rawAngle !== "" && !Number.isFinite(Number(rawAngle))) {
        return "渐变角度必须是有效数字";
    }
    return "";
}

export function removeProfileCardLayoutMetadata(metadataJson) {
    const metadata = parseMetadataObject(metadataJson);
    delete metadata.profile_card_layout;
    return stringifyMetadata(metadata);
}

export function metadataWithProfileCardLayout(metadataJson, layout) {
    const metadata = parseMetadataObject(metadataJson);
    if (layout) {
        metadata.profile_card_layout = layout;
    } else {
        delete metadata.profile_card_layout;
    }
    return stringifyMetadata(metadata);
}

function parseMetadataObject(metadataJson) {
    const normalized = String(metadataJson || "").trim();
    if (!normalized) {
        return {};
    }
    try {
        const parsed = JSON.parse(normalized);
        return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
    } catch {
        return {};
    }
}

function stringifyMetadata(metadata) {
    const clean = {};
    Object.entries(metadata || {}).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== "") {
            clean[key] = value;
        }
    });
    return Object.keys(clean).length ? JSON.stringify(clean) : emptyResourceMetadata;
}

function splitRoomNameStyleValues(value) {
    return String(value || "")
        .split(/[\s,，]+/)
        .map((item) => item.trim())
        .filter(Boolean);
}

function validateRoomNameStyle(style) {
    if (
        !style.textColors.length ||
        style.textColors.length > 8 ||
        style.textColors.some((color) => !roomNameColorPattern.test(color))
    ) {
        return "invalid colors";
    }
    if (
        style.stops.length &&
        (style.stops.length !== style.textColors.length ||
            style.stops.some((stop) => !Number.isFinite(stop) || stop < 0 || stop > 1) ||
            style.stops.some((stop, index) => index > 0 && stop < style.stops[index - 1]))
    ) {
        return "invalid stops";
    }
    if (style.angleDegrees !== null && !Number.isFinite(style.angleDegrees)) {
        return "invalid angle";
    }
    return "";
}
