import { useCallback } from "react";
import { sanitizeAgentMetadata } from "./agentSessionMetadata";
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 selectProfileForContextSeeding(input) {
    const { profiles, profileId, profileName } = input;
    try {
        if (profileId) {
            const byId = profiles.find((profile) => profile.id === profileId);
            if (byId)
                return byId;
        }
        if (profileName) {
            const byName = profiles.find((profile) => profile.name === profileName);
            if (byName)
                return byName;
        }
        return profiles[0];
    }
    catch {
        return undefined;
    }
}
function shouldSeedEditorContext(profile) {
    try {
        const mode = profile?.editorContextMode;
        if (mode !== undefined) {
            return mode === "onCreate" || mode === "live";
        }
        return true;
    }
    catch {
        return true;
    }
}
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, profiles, currentItemDescriptor, buildEditorContextPayload, messagesRef, actions, setAgent, setAgentMetadata, setError, setPrompt, } = input;
    return useCallback(() => {
        const hasExistingMessages = messagesRef.current.length > 0;
        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();
        const profileForSeeding = selectProfileForContextSeeding({
            profiles,
            profileId: initialProfileId,
            profileName: initialProfileName,
        });
        const shouldSeedContext = shouldSeedEditorContext(profileForSeeding);
        const localContext = currentItemDescriptor && shouldSeedContext
            ? buildEditorContextPayload(currentItemDescriptor)
            : null;
        const nextMetadata = mergeInitialMetadataWithLocalContext({
            initialMetadata,
            localContext,
        });
        if (nextMetadata) {
            setAgentMetadata(sanitizeAgentMetadata(nextMetadata));
            try {
                const maybePrompt = nextMetadata?.additionalData
                    ?.initialPrompt;
                if (typeof maybePrompt === "string" && maybePrompt.trim()) {
                    setPrompt(maybePrompt);
                }
            }
            catch { }
        }
        return true;
    }, [
        actions,
        agentStub,
        buildEditorContextPayload,
        currentItemDescriptor,
        initialMetadata,
        messagesRef,
        profiles,
        setAgent,
        setAgentMetadata,
        setError,
        setPrompt,
    ]);
}
//# sourceMappingURL=useAgentDraftInitializer.js.map