import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { createIconResolver, fallbackIconSvg, } from "@stack-scribe/core";
import { awsGroupIconDefinitions, createAwsIconRegistry } from "./index.js";
import { nodeTypeToIcon } from "./catalog.js";
import { resolveNodeType } from "./node-resolver.js";
const moduleDir = fileURLToPath(new URL(".", import.meta.url));
const iconsDirectory = process.env.STACK_SCRIBE_AWS_ICONS_DIR
    ? resolve(process.env.STACK_SCRIBE_AWS_ICONS_DIR)
    : resolve(moduleDir, "..", "icons");
const iconCache = new Map();
export { fallbackIconSvg };
export function getAwsIconsDirectory() {
    return iconsDirectory;
}
export function getAwsIconPath(type) {
    const resolvedType = resolveNodeType(type);
    if (!resolvedType) {
        return undefined;
    }
    return resolve(getAwsIconsDirectory(), nodeTypeToIcon[resolvedType]);
}
export function getAwsGroupIconPath(style) {
    const groupIcon = awsGroupIconDefinitions.find((definition) => definition.key === style);
    if (!groupIcon) {
        return undefined;
    }
    return resolve(getAwsIconsDirectory(), groupIcon.assetPath);
}
export function getAwsIcon(type) {
    const iconPath = getAwsIconPath(type);
    if (!iconPath) {
        return fallbackIconSvg;
    }
    const cached = iconCache.get(iconPath);
    if (cached) {
        return cached;
    }
    try {
        const svg = readFileSync(iconPath, "utf8");
        iconCache.set(iconPath, svg);
        return svg;
    }
    catch {
        return fallbackIconSvg;
    }
}
export function getAwsGroupIcon(style) {
    const iconPath = getAwsGroupIconPath(style);
    if (!iconPath) {
        return null;
    }
    const cached = iconCache.get(iconPath);
    if (cached) {
        return cached;
    }
    try {
        const svg = readFileSync(iconPath, "utf8");
        iconCache.set(iconPath, svg);
        return svg;
    }
    catch {
        return null;
    }
}
export function clearAwsIconCache() {
    iconCache.clear();
}
export function createAwsIconAssetLoader() {
    return {
        getIconSvg(type) {
            const icon = getAwsIcon(type);
            return icon === fallbackIconSvg ? undefined : icon;
        },
        getGroupIconSvg(styleOrType) {
            return getAwsGroupIcon(styleOrType) ?? undefined;
        },
    };
}
export function createAwsIconResolver() {
    return createIconResolver(createAwsIconRegistry(), createAwsIconAssetLoader());
}
//# sourceMappingURL=node-fs-loader.js.map