import type {Gallery_Response} from "./gallery_types";

const KNOWN_RESPONSE_TYPES = new Set(["catalog", "case_state", "refresh_state", "observer_state", "error"]);
export class Gallery_Protocol_Error extends Error {}

export function parse_gallery_response(raw: string): Gallery_Response | null {
    let value: unknown;
    try { value = JSON.parse(raw); } catch { throw new Gallery_Protocol_Error("后端返回了无效 JSON"); }
    if (!value || typeof value !== "object" || Array.isArray(value)) throw new Gallery_Protocol_Error("后端响应必须是对象");
    const type = (value as {type?: unknown}).type;
    if (typeof type !== "string") throw new Gallery_Protocol_Error("后端响应缺少 type");
    if (!KNOWN_RESPONSE_TYPES.has(type)) return null;
    return value as Gallery_Response;
}
