import { generatePageContext, getCachedContext, } from "./contextService";
import { post } from "./serviceHelper";
export function normalizeTextCompletion(completion) {
    return (completion || "").replace(/\s+/g, " ").trimStart();
}
export async function buildTextCompletionContext(editContext, field, value, selectionStart, selectionEnd) {
    const parts = [];
    const cachedContext = getCachedContext(editContext);
    const activeSlotContext = editContext.getActiveSlotContext?.();
    const pageViewContext = activeSlotContext?.primaryPageViewContext;
    const pageContext = cachedContext ||
        (pageViewContext
            ? await generatePageContext(editContext, pageViewContext)
            : null);
    if (pageContext?.abstract) {
        parts.push(`Page context: ${pageContext.abstract}`);
    }
    parts.push(`Field: ${field.displayName || field.name || field.id}`, `Field type: ${field.type}`);
    const beforeCursor = value.slice(Math.max(0, selectionStart - 1000), selectionStart);
    const afterCursor = value.slice(selectionEnd, selectionEnd + 500);
    if (beforeCursor.trim()) {
        parts.push(`Text before cursor: ${beforeCursor}`);
    }
    if (afterCursor.trim()) {
        parts.push(`Text after cursor: ${afterCursor}`);
    }
    return parts.join("\n\n");
}
export async function getTextCompletion({ editContext, field, value, selectionStart, selectionEnd, signal, }) {
    const contextInfo = await buildTextCompletionContext(editContext, field, value, selectionStart, selectionEnd);
    const textToComplete = value.slice(0, selectionStart);
    const response = await post("/parhelia/agent/GetTextCompletion", {
        textToComplete,
        contextInfo,
    }, undefined, signal);
    if (signal?.aborted) {
        return "";
    }
    if (response.type === "success") {
        return normalizeTextCompletion(response.data?.completion);
    }
    console.warn("Failed to get text completion", response);
    return "";
}
//# sourceMappingURL=textCompletionService.js.map