import { executeAssetSummary } from "../run/flows/asset/summary.js";
import { scopeTranscriptCacheForDiarization } from "../shared/transcript-diarization-cache-scope.js";
import { createRunFlowContexts } from "./flow-contexts.js";
import { createExecutableRunModel, createRunModelRuntime, } from "./model-runtime.js";
function chainCallback(first, second) {
    return (...args) => {
        first?.(...args);
        second(...args);
    };
}
export function bindSummarizeExecutionEvents(prepared, emit) {
    const baseHooks = prepared.urlFlowContext.hooks;
    const assetSummaryContext = prepared.assetSummaryContext
        ? {
            ...prepared.assetSummaryContext,
            onSummaryCached: chainCallback(prepared.assetSummaryContext.onSummaryCached, (cached) => emit({ type: "summary-cache", cached })),
        }
        : null;
    const summarizeAsset = assetSummaryContext
        ? (args) => executeAssetSummary(assetSummaryContext, args)
        : baseHooks.summarizeAsset;
    return {
        assetSummaryContext,
        isYoutubeUrl: prepared.isYoutubeUrl,
        urlFlowContext: {
            ...prepared.urlFlowContext,
            hooks: {
                ...baseHooks,
                onModelChosen: chainCallback(baseHooks.onModelChosen, (modelId) => emit({ type: "model-selected", modelId })),
                onExtracted: chainCallback(baseHooks.onExtracted, (content) => emit({ type: "content-extracted", content })),
                onSlidesExtracted: chainCallback(baseHooks.onSlidesExtracted, (slides) => emit({ type: "slides-extracted", slides })),
                onSlidesProgress: chainCallback(baseHooks.onSlidesProgress, (text) => emit({ type: "slides-progress", text })),
                onSlidesDone: chainCallback(baseHooks.onSlidesDone, (result) => emit({ type: "slides-completed", ...result })),
                onSlideChunk: chainCallback(baseHooks.onSlideChunk, ({ slide, meta }) => emit({ type: "slide", slide, meta })),
                onLinkPreviewProgress: chainCallback(baseHooks.onLinkPreviewProgress, (event) => emit({ type: "extraction-progress", event })),
                onSummaryCached: chainCallback(baseHooks.onSummaryCached, (cached) => emit({ type: "summary-cache", cached })),
                summarizeAsset,
            },
        },
    };
}
export function createSummarizeFlowFlags(spec, flow) {
    return {
        timeoutMs: spec.timeoutMs,
        maxExtractCharacters: flow.maxExtractCharacters === undefined
            ? spec.maxExtractCharacters
            : flow.maxExtractCharacters,
        retries: spec.retries,
        format: spec.format,
        markdownMode: spec.markdownMode,
        preprocessMode: spec.preprocessMode,
        youtubeMode: spec.youtubeMode,
        firecrawlMode: spec.firecrawlMode,
        videoMode: spec.videoMode,
        embeddedVideoMode: spec.embeddedVideoMode,
        transcriptTimestamps: flow.transcriptTimestamps ?? spec.transcriptTimestamps,
        transcriptDiarization: spec.transcriptDiarization,
        speakerIdentification: flow.speakerIdentification ?? null,
        outputLanguage: spec.outputLanguage,
        lengthArg: spec.lengthArg,
        forceSummary: spec.forceSummary,
        promptOverride: spec.promptOverride,
        lengthInstruction: spec.lengthInstruction,
        languageInstruction: spec.languageInstruction,
        summaryCacheBypass: flow.summaryCacheBypass ?? false,
        maxOutputTokensArg: spec.maxOutputTokensArg,
        json: flow.json ?? false,
        extractMode: flow.extractMode,
        metricsEnabled: flow.metricsEnabled ?? false,
        metricsDetailed: flow.metricsDetailed ?? false,
        shouldComputeReport: flow.shouldComputeReport ?? false,
        runStartedAtMs: flow.runStartedAtMs,
        verbose: flow.verbose ?? false,
        verboseColor: flow.verboseColor ?? false,
        progressEnabled: flow.progressEnabled ?? false,
        streamMode: flow.streamMode ?? (flow.streamingEnabled ? "on" : "off"),
        streamingEnabled: flow.streamingEnabled,
        plain: flow.plain ?? true,
        configPath: spec.configPath,
        configModelLabel: spec.configModelLabel,
        slides: flow.slides ?? null,
        slidesDebug: flow.slidesDebug ?? false,
        slidesOutput: flow.slidesOutput ?? false,
        throwOnAssetLikeHtmlError: flow.throwOnAssetLikeHtmlError,
    };
}
export function createSummarizeModelResources(options) {
    const { resolvedRun, env, metricsEnv = env, fetchImpl, execFileImpl, streamingEnabled, summaryStream, requestOptions, log, trace, } = options;
    const { context, envForRun } = resolvedRun.bindings;
    const runtime = createRunModelRuntime({
        context,
        env,
        envForRun,
        metricsEnv,
        fetchImpl,
        execFileImpl,
        maxOutputTokensArg: resolvedRun.spec.maxOutputTokensArg,
        timeoutMs: resolvedRun.spec.timeoutMs,
        retries: resolvedRun.spec.retries,
        streamingEnabled,
        requestOptions,
        log,
        trace,
    });
    const model = createExecutableRunModel({
        spec: resolvedRun.bindings.model,
        runtime,
        context,
        allowAutoCliFallback: resolvedRun.spec.allowAutoCliFallback,
        summaryStream,
        requestOptions,
    });
    return { context, envForRun, runtime, model };
}
export function createSummarizeExecutionResources(options) {
    const { resolvedRun, flow } = options;
    const { spec } = resolvedRun;
    const modelResources = createSummarizeModelResources({
        resolvedRun,
        env: options.env,
        metricsEnv: options.metricsEnv,
        fetchImpl: options.fetchImpl,
        execFileImpl: options.execFileImpl,
        streamingEnabled: flow.streamingEnabled,
        summaryStream: options.summaryStream,
        requestOptions: options.requestOptions,
        log: options.log,
        trace: options.trace,
    });
    const { metrics } = modelResources.runtime;
    const cacheState = scopeTranscriptCacheForDiarization(options.cacheState, spec.transcriptDiarization);
    const flags = createSummarizeFlowFlags(spec, flow);
    const contexts = createRunFlowContexts({
        cacheState,
        mediaCache: options.mediaCache,
        io: {
            env: options.env,
            envForRun: modelResources.envForRun,
            stdout: options.stdout,
            stderr: options.stderr,
            execFileImpl: options.execFileImpl,
            fetch: metrics.trackedFetch,
            ...(options.urlFetch ? { urlFetch: options.urlFetch } : {}),
        },
        flags,
        model: modelResources.model,
        runtimeHooks: {
            setTranscriptionCost: metrics.setTranscriptionCost,
            ...options.adapterHooks,
            buildReport: metrics.buildReport,
            estimateCostUsd: metrics.estimateCostUsd,
        },
        eventHooks: options.eventHooks,
        assetSummaryOverrides: options.assetSummaryOverrides,
        perfTrace: options.perfTrace,
    });
    return { ...contexts, cacheState, modelResources };
}
//# sourceMappingURL=execution-resources.js.map