import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";

const EXTENSION = "ethanfel.prompt_builder.preview_any_text";
const NODE_NAME = "SxCPPreviewAnyAsText";

function isPreviewTextNode(node) {
    return node?.comfyClass === NODE_NAME || node?.type === NODE_NAME;
}

function getNodeById(id) {
    return app.graph?.getNodeById?.(Number(id)) || app.graph?._nodes_by_id?.[id] || app.graph?._nodes_by_id?.[Number(id)];
}

function widget(node, name) {
    return node.widgets?.find((item) => item.name === name);
}

function outputPreviewText(output) {
    const raw = output?.preview_text;
    if (Array.isArray(raw)) return raw[0] ?? "";
    return raw ?? "";
}

function setPreviewWidget(node, text) {
    const preview = widget(node, "preview_text");
    if (!preview) return;
    preview.value = text;
    if (preview.inputEl) preview.inputEl.value = text;
    preview.callback?.(text, app.canvas, node);
    node.setDirtyCanvas?.(true, true);
    app.graph?.setDirtyCanvas?.(true, true);
}

app.registerExtension({
    name: EXTENSION,

    async setup() {
        api.addEventListener("executed", ({detail}) => {
            const node = getNodeById(detail?.display_node ?? detail?.node);
            if (!isPreviewTextNode(node)) return;
            const text = outputPreviewText(detail?.output || {});
            setPreviewWidget(node, text);
        });
    },
});
