import { useCallback } from "react";
import { sanitizeAgentMetadata } from "./agentSessionMetadata";
import { normalizeAgentId } from "../agentMessageHelpers";
function getInitialProfileId(initialMetadata) {
    try {
        return initialMetadata?.additionalData?.profileId;
    }
    catch {
        return undefined;
    }
}
function getInitialProfileName(initialMetadata) {
    try {
        return (initialMetadata?.additionalData?.profileName ||
            initialMetadata?.profile ||
            undefined);
    }
    catch {
        return undefined;
    }
}
function mergeInitialMetadataWithLocalContext(input) {
    const { initialMetadata, localContext } = input;
    if (!initialMetadata) {
        return localContext;
    }
    const base = { ...initialMetadata };
    if (!localContext) {
        return base;
    }
    if (localContext.items && localContext.items.length) {
        const targetPages = Array.isArray(base.items) ? [...base.items] : [];
        const existingKeys = new Set(targetPages.map((page) => `${page.id}-${page.language || ""}-${page.version || ""}`));
        const additions = localContext.items.filter((page) => !existingKeys.has(`${page.id}-${page.language || ""}-${page.version || ""}`));
        if (additions.length) {
            base.items = [...targetPages, ...additions];
        }
    }
    if (localContext.components && localContext.components.length) {
        const currentComponents = Array.isArray(base.components)
            ? base.components
            : [];
        const existingIds = new Set(currentComponents.map((component) => component.componentId));
        const additions = localContext.components.filter((component) => !!component?.componentId && !existingIds.has(component.componentId));
        if (additions.length) {
            base.components = [...currentComponents, ...additions];
        }
    }
    if (!base.field && localContext.field) {
        base.field = localContext.field;
    }
    return base;
}
export function useAgentDraftInitializer(input) {
    const { agentStub, initialMetadata, messagesRef, actions, setAgent, setAgentMetadata, setError, setPrompt, } = input;
    return useCallback(() => {
        const draftAgentId = normalizeAgentId(agentStub.id);
        const hasExistingMessages = messagesRef.current.some((message) => normalizeAgentId(message.agentId) === draftAgentId);
        if (agentStub.status !== "new" || agentStub.userId || hasExistingMessages) {
            return false;
        }
        const initialProfileId = getInitialProfileId(initialMetadata);
        const initialProfileName = getInitialProfileName(initialMetadata);
        setAgent({
            ...agentStub,
            messages: [],
            status: "new",
            updatedDate: new Date().toISOString(),
            createdDate: new Date().toISOString(),
            id: agentStub.id,
            name: agentStub.name,
            model: "",
            currency: "USD",
            profileId: initialProfileId || "",
            profileName: initialProfileName || "",
            totalTokensUsed: 0,
            totalInputTokens: 0,
            totalOutputTokens: 0,
            totalCachedInputTokens: 0,
            totalInputTokenCost: 0,
            totalOutputTokenCost: 0,
            totalCachedInputTokenCost: 0,
            totalImageCost: 0,
            totalCost: 0,
            messageCount: 0,
        });
        messagesRef.current = [];
        actions.replaceTranscript([]);
        setError(null);
        actions.finishReady();
        // Editor context is no longer auto-seeded on create. The user opts in to
        // the currently viewed page/component/field via the "include currently
        // viewed page" checkbox, or pins it explicitly. Only explicit invocation
        // context carried on initialMetadata (e.g. a review comment or field) is
        // kept here.
        const nextMetadata = mergeInitialMetadataWithLocalContext({
            initialMetadata,
            localContext: null,
        });
        if (nextMetadata) {
            setAgentMetadata(sanitizeAgentMetadata(nextMetadata));
            try {
                const maybePrompt = nextMetadata?.additionalData
                    ?.initialPrompt;
                if (typeof maybePrompt === "string" && maybePrompt.trim()) {
                    setPrompt(maybePrompt);
                }
            }
            catch { }
        }
        return true;
    }, [
        actions,
        agentStub,
        initialMetadata,
        messagesRef,
        setAgent,
        setAgentMetadata,
        setError,
        setPrompt,
    ]);
}
//# sourceMappingURL=useAgentDraftInitializer.js.map