import { getComponentById } from "../componentTreeHelper";
function idsMatch(left, right) {
    const normalize = (value) => (value ?? "").replace(/[{}-]/g, "").toLowerCase();
    const a = normalize(left);
    const b = normalize(right);
    return !!a && !!b && a === b;
}
function getRelatedItem(comment, itemId) {
    if (!itemId)
        return undefined;
    return comment.relatedItems?.find((item) => idsMatch(item.itemId, itemId));
}
function buildCommentTargetPromptParts(comment) {
    const parts = [];
    const mainItemId = comment.mainItemId;
    const targetItemId = comment.itemId;
    if (comment.mainItemName || mainItemId) {
        parts.push(`Page: ${comment.mainItemName || "unknown"}${mainItemId ? ` (${mainItemId})` : ""}`);
    }
    if (targetItemId && !idsMatch(targetItemId, mainItemId)) {
        parts.push(`Anchored item/component: ${comment.itemName || "unknown"} (${targetItemId})`);
    }
    if (comment.fieldId || comment.fieldName) {
        parts.push(`Field: ${comment.fieldName || "unknown"}${comment.fieldId ? ` (${comment.fieldId})` : ""}`);
    }
    return parts;
}
/**
 * Opens the Agents panel and seeds it with context from a review comment.
 * Safe to call with an undefined editContext; it will no-op.
 */
export function openAiAgentForComment(comment, editContext) {
    if (!editContext)
        return;
    const hasAgentsPanel = editContext.configuration?.editor?.sidebars?.some((sidebar) => sidebar.id === "agents-panel");
    if (!hasAgentsPanel) {
        return;
    }
    // Respect quota if available
    if (editContext.isQuotaExceeded) {
        editContext.showToast?.("AI quota exceeded. Please try again later or adjust settings.");
        return;
    }
    const selectedText = (() => {
        if (typeof comment.rangeStart === "number" &&
            typeof comment.rangeEnd === "number" &&
            comment.fieldValue) {
            try {
                return comment.fieldValue.substring(Math.max(0, comment.rangeStart), Math.max(comment.rangeStart, comment.rangeEnd));
            }
            catch {
                return undefined;
            }
        }
        return undefined;
    })();
    const promptParts = [];
    const text = (comment.text || "").trim();
    if (text)
        promptParts.push(`Comment: "${text}"`);
    if (selectedText)
        promptParts.push(`Selected text: "${selectedText}"`);
    promptParts.push(...buildCommentTargetPromptParts(comment));
    const initialPrompt = promptParts.length > 0
        ? `Please help resolve this review comment. ${promptParts.join(" | ")}`
        : "Please help resolve this review comment.";
    try {
        if (editContext.isMobile) {
            editContext.openSidebar("agents-panel");
        }
        else {
            editContext.setShowAgentsPanel(true);
        }
        const mainItemId = comment.mainItemId || editContext.currentItemDescriptor?.id;
        const mainRelatedItem = getRelatedItem(comment, mainItemId);
        const targetRelatedItem = getRelatedItem(comment, comment.itemId);
        const pageItem = mainItemId && comment.language && comment.version
            ? {
                id: mainItemId,
                language: comment.language,
                version: comment.version,
                name: comment.mainItemName ||
                    mainRelatedItem?.itemName ||
                    editContext.item?.name,
                path: mainRelatedItem?.itemPath || editContext.item?.path,
            }
            : undefined;
        const componentIds = Array.from(new Set([
            ...(editContext.selection || []),
            comment.itemId && !idsMatch(comment.itemId, mainItemId)
                ? comment.itemId
                : undefined,
        ].filter((id) => !!id)));
        const components = componentIds
            .map((componentId) => {
            let component;
            try {
                component = editContext.page
                    ? getComponentById(componentId, editContext.page)
                    : undefined;
            }
            catch {
                component = undefined;
            }
            if (!component && !idsMatch(componentId, comment.itemId)) {
                return undefined;
            }
            return {
                componentId,
                componentName: component?.datasourceItem?.name ||
                    component?.name ||
                    (idsMatch(componentId, comment.itemId)
                        ? comment.itemName || targetRelatedItem?.itemName
                        : undefined),
                componentType: component?.type || undefined,
                renderingItemId: component?.rendering?.id || undefined,
                pageItem: pageItem,
            };
        })
            .filter((component) => !!component && !!component.pageItem);
        const field = comment.fieldId && comment.itemId
            ? {
                fieldId: comment.fieldId,
                fieldName: comment.fieldName,
                item: {
                    id: comment.itemId,
                    language: comment.language,
                    version: comment.version,
                    name: comment.itemName || targetRelatedItem?.itemName,
                    path: targetRelatedItem?.itemPath,
                },
            }
            : undefined;
        const initialMetadata = {
            items: [
                {
                    id: mainItemId,
                    language: comment.language,
                    version: comment.version,
                    name: comment.mainItemName ||
                        mainRelatedItem?.itemName ||
                        editContext.item?.name,
                    path: mainRelatedItem?.itemPath || editContext.item?.path,
                },
            ],
            currentItemId: mainItemId,
            components: components.length > 0 ? components : undefined,
            field,
            comment: {
                id: comment.id,
                text: comment.text,
                fieldName: comment.fieldName,
                itemName: comment.itemName,
                author: comment.author,
                selectedText: selectedText,
                rangeStart: comment.rangeStart,
                rangeEnd: comment.rangeEnd,
            },
            additionalData: {
                initialPrompt,
                profileId: editContext.parheliaSettings?.commentResolveProfileId || undefined,
                profileName: editContext.parheliaSettings?.commentResolveProfileName || undefined,
            },
        };
        // Ask Agents UI to open a new terminal seeded with this metadata
        const dispatchEvent = () => {
            try {
                window.dispatchEvent(new CustomEvent("editor:addNewAgent", {
                    detail: { metadata: initialMetadata },
                }));
            }
            catch { }
        };
        if (editContext.isMobile) {
            // 500ms delay on mobile to ensure the sidebar is mounted and listening.
            // Layout transitions on mobile can take time.
            setTimeout(dispatchEvent, 500);
        }
        else {
            dispatchEvent();
        }
    }
    catch (e) {
        console.error("Failed to start agent for comment:", e);
        editContext.showToast?.("Failed to start AI agent for this comment.");
    }
}
//# sourceMappingURL=commentAi.js.map