import { basename } from "node:path";
import { error, info } from "../logging.js";
import { getSettings } from "../settings.js";
const CODE_SNIPPETS_API_URL = process.env.SPEAKEASY_CODE_SNIPPETS_API_URL ?? "https://api.speakeasy.com";
export async function generateCodeSnippets(docsData, specContents) {
    const { spec, codeSamples } = getSettings();
    if (!codeSamples) {
        info("Code samples not enabled, skipping code snippets generation");
        return {};
    }
    const docsCodeSnippets = {};
    const specFilename = spec && basename(spec);
    // create a by operationId map of the operation chunks
    const operationChunksByOperationId = new Map();
    for (const chunk of docsData.values()) {
        if (chunk.chunkType === "operation") {
            operationChunksByOperationId.set(chunk.chunkData.operationId, chunk);
        }
    }
    try {
        for (const language of codeSamples) {
            const formData = new FormData();
            const blob = new Blob([specContents]);
            formData.append("language", language.language);
            formData.append("schema_file", blob, specFilename);
            formData.append("package_name", language.packageName);
            formData.append("sdk_class_name", language.sdkClassName);
            const res = await fetch(`${CODE_SNIPPETS_API_URL}/v1/code_sample/preview`, {
                method: "POST",
                body: formData,
            });
            const json = (await res.json());
            if (!res.ok) {
                const error = json;
                throw new Error(`Failed to generate code sample: ${error.message}`);
            }
            const codeSnippets = json.snippets.map((snippet) => ({
                ...snippet,
                packageName: language.packageName,
            }));
            for (const snippet of codeSnippets) {
                const chunk = operationChunksByOperationId.get(snippet.operationId);
                // only set the usage snippet if the operation id exists in the spec
                if (chunk) {
                    docsCodeSnippets[chunk.id] ??= {};
                    // Won't be null due to the above line
                    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                    docsCodeSnippets[chunk.id][language.language] = snippet;
                }
            }
        }
    }
    catch (err) {
        error(`There was an error generating code snippets`, err);
        return {};
    }
    return docsCodeSnippets;
}
//# sourceMappingURL=generateCodeSnippets.js.map