import { buildPageViewerNotOpenFailure, validateBrowserBoundCaptureRequest, } from "./browserBoundCapture";
import { createCaptureRequestId, readTitleFromHtml } from "./captureShared";
function getActivePageViewContext(editContext) {
    return editContext.getActiveSlotContext?.()?.primaryPageViewContext;
}
async function capturePageDomThroughBridge(pageViewContext) {
    if (!pageViewContext?.requestBridgeCaptureDom)
        return null;
    try {
        const result = await pageViewContext.requestBridgeCaptureDom({
            requestId: createCaptureRequestId("capture-dom"),
        });
        if (result.error) {
            return {
                success: false,
                scope: "page",
                error: result.error,
            };
        }
        const html = result.html ?? "";
        if (!html.trim()) {
            return {
                success: false,
                scope: "page",
                error: "The current page DOM is empty.",
            };
        }
        return {
            success: true,
            scope: "page",
            html,
            length: html.length,
            documentTitle: readTitleFromHtml(html),
        };
    }
    catch (error) {
        return {
            success: false,
            scope: "page",
            error: error instanceof Error
                ? error.message
                : "Failed to capture the current page DOM through the host bridge.",
        };
    }
}
export async function capturePageDom(request, _params, editContext) {
    if (!editContext) {
        return buildPageViewerNotOpenFailure({
            request,
            editContext,
            scope: "page",
        });
    }
    const pageViewContext = getActivePageViewContext(editContext);
    if (!pageViewContext) {
        return buildPageViewerNotOpenFailure({
            request,
            editContext,
            scope: "page",
        });
    }
    const validationFailure = validateBrowserBoundCaptureRequest({
        request,
        editContext,
        scope: "page",
    });
    if (validationFailure) {
        return validationFailure;
    }
    const bridgeResult = await capturePageDomThroughBridge(pageViewContext);
    if (bridgeResult)
        return bridgeResult;
    return {
        success: false,
        scope: "page",
        error: "The current page bridge is not ready to capture DOM.",
    };
}
//# sourceMappingURL=capturePageDom.js.map