import { clearApiProviders, registerApiProvider } from "../api-registry.js";
import { AssistantMessageEventStream } from "../utils/event-stream.js";
const dynamicImport = (specifier) => import(specifier);
// ---------------------------------------------------------------------------
// Generic lazy-load infrastructure
// ---------------------------------------------------------------------------
/**
 * Module cache for lazily-loaded provider modules.
 * Keyed by specifier string; value is the resolved module object.
 */
const moduleCache = new Map();
/**
 * Clear all cached provider modules.
 * Called by resetApiProviders() so re-registration gets fresh lazy wrappers.
 */
function clearModuleCache() {
    moduleCache.clear();
}
/**
 * Load a provider module lazily, caching it for subsequent calls.
 */
async function loadProviderModule(specifier) {
    const cached = moduleCache.get(specifier);
    if (cached) {
        return cached;
    }
    const mod = await dynamicImport(specifier);
    moduleCache.set(specifier, mod);
    return mod;
}
/**
 * Create an error AssistantMessage for import failures.
 * Generalized from the original Bedrock-only version.
 */
function createLazyLoadErrorMessage(model, error) {
    return {
        role: "assistant",
        content: [],
        api: model.api,
        provider: model.provider,
        model: model.id,
        usage: {
            input: 0,
            output: 0,
            cacheRead: 0,
            cacheWrite: 0,
            totalTokens: 0,
            cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
        },
        stopReason: "error",
        errorMessage: error instanceof Error ? error.message : String(error),
        timestamp: Date.now(),
    };
}
/**
 * Forward events from a source async iterable into a target event stream.
 */
function forwardStream(target, source) {
    (async () => {
        for await (const event of source) {
            target.push(event);
        }
        target.end();
    })();
}
/**
 * Create a lazy stream wrapper for a provider.
 *
 * On first call, the provider module is dynamically imported and cached.
 * The wrapper immediately returns an AssistantMessageEventStream so callers
 * get a synchronous return value; the actual provider stream is piped through
 * once the import resolves.
 */
function createLazyStream(specifier, streamFnName) {
    return (model, context, options) => {
        const outer = new AssistantMessageEventStream();
        loadProviderModule(specifier)
            .then((mod) => {
            const streamFn = mod[streamFnName];
            const inner = streamFn(model, context, options);
            forwardStream(outer, inner);
        })
            .catch((error) => {
            const message = createLazyLoadErrorMessage(model, error);
            outer.push({ type: "error", reason: "error", error: message });
            outer.end(message);
        });
        return outer;
    };
}
let bedrockProviderModuleOverride;
export function setBedrockProviderModule(module) {
    bedrockProviderModuleOverride = module;
}
// Bedrock uses a special loader that respects the override hook
const BEDROCK_PROVIDER_SPECIFIER = "./amazon-" + "bedrock.js";
async function loadBedrockProviderModule() {
    if (bedrockProviderModuleOverride) {
        return bedrockProviderModuleOverride;
    }
    return loadProviderModule(BEDROCK_PROVIDER_SPECIFIER);
}
function streamBedrockLazy(model, context, options) {
    const outer = new AssistantMessageEventStream();
    loadBedrockProviderModule()
        .then((module) => {
        const inner = module.streamBedrock(model, context, options);
        forwardStream(outer, inner);
    })
        .catch((error) => {
        const message = createLazyLoadErrorMessage(model, error);
        outer.push({ type: "error", reason: "error", error: message });
        outer.end(message);
    });
    return outer;
}
function streamSimpleBedrockLazy(model, context, options) {
    const outer = new AssistantMessageEventStream();
    loadBedrockProviderModule()
        .then((module) => {
        const inner = module.streamSimpleBedrock(model, context, options);
        forwardStream(outer, inner);
    })
        .catch((error) => {
        const message = createLazyLoadErrorMessage(model, error);
        outer.push({ type: "error", reason: "error", error: message });
        outer.end(message);
    });
    return outer;
}
// ---------------------------------------------------------------------------
// Provider module specifiers (string concatenation defeats static analysis
// to prevent bundlers from eagerly resolving these imports)
// ---------------------------------------------------------------------------
const ANTHROPIC_SPECIFIER = "./anthro" + "pic.js";
const ANTHROPIC_VERTEX_SPECIFIER = "./anthropic-" + "vertex.js";
const AZURE_OPENAI_SPECIFIER = "./azure-openai-" + "responses.js";
const GOOGLE_SPECIFIER = "./goo" + "gle.js";
const GOOGLE_GEMINI_CLI_SPECIFIER = "./google-gemini-" + "cli.js";
const GOOGLE_VERTEX_SPECIFIER = "./google-" + "vertex.js";
const MISTRAL_SPECIFIER = "./mis" + "tral.js";
const OPENAI_CODEX_SPECIFIER = "./openai-codex-" + "responses.js";
const OPENAI_COMPLETIONS_SPECIFIER = "./openai-" + "completions.js";
const OPENAI_RESPONSES_SPECIFIER = "./openai-" + "responses.js";
// ---------------------------------------------------------------------------
// Registration
// ---------------------------------------------------------------------------
function registerBuiltInApiProviders() {
    // Anthropic
    registerApiProvider({
        api: "anthropic-messages",
        stream: createLazyStream(ANTHROPIC_SPECIFIER, "streamAnthropic"),
        streamSimple: createLazyStream(ANTHROPIC_SPECIFIER, "streamSimpleAnthropic"),
    });
    // OpenAI Completions
    registerApiProvider({
        api: "openai-completions",
        stream: createLazyStream(OPENAI_COMPLETIONS_SPECIFIER, "streamOpenAICompletions"),
        streamSimple: createLazyStream(OPENAI_COMPLETIONS_SPECIFIER, "streamSimpleOpenAICompletions"),
    });
    // Mistral
    registerApiProvider({
        api: "mistral-conversations",
        stream: createLazyStream(MISTRAL_SPECIFIER, "streamMistral"),
        streamSimple: createLazyStream(MISTRAL_SPECIFIER, "streamSimpleMistral"),
    });
    // OpenAI Responses
    registerApiProvider({
        api: "openai-responses",
        stream: createLazyStream(OPENAI_RESPONSES_SPECIFIER, "streamOpenAIResponses"),
        streamSimple: createLazyStream(OPENAI_RESPONSES_SPECIFIER, "streamSimpleOpenAIResponses"),
    });
    // Azure OpenAI Responses
    registerApiProvider({
        api: "azure-openai-responses",
        stream: createLazyStream(AZURE_OPENAI_SPECIFIER, "streamAzureOpenAIResponses"),
        streamSimple: createLazyStream(AZURE_OPENAI_SPECIFIER, "streamSimpleAzureOpenAIResponses"),
    });
    // OpenAI Codex Responses
    registerApiProvider({
        api: "openai-codex-responses",
        stream: createLazyStream(OPENAI_CODEX_SPECIFIER, "streamOpenAICodexResponses"),
        streamSimple: createLazyStream(OPENAI_CODEX_SPECIFIER, "streamSimpleOpenAICodexResponses"),
    });
    // Google Generative AI
    registerApiProvider({
        api: "google-generative-ai",
        stream: createLazyStream(GOOGLE_SPECIFIER, "streamGoogle"),
        streamSimple: createLazyStream(GOOGLE_SPECIFIER, "streamSimpleGoogle"),
    });
    // Google Gemini CLI
    registerApiProvider({
        api: "google-gemini-cli",
        stream: createLazyStream(GOOGLE_GEMINI_CLI_SPECIFIER, "streamGoogleGeminiCli"),
        streamSimple: createLazyStream(GOOGLE_GEMINI_CLI_SPECIFIER, "streamSimpleGoogleGeminiCli"),
    });
    // Google Vertex
    registerApiProvider({
        api: "google-vertex",
        stream: createLazyStream(GOOGLE_VERTEX_SPECIFIER, "streamGoogleVertex"),
        streamSimple: createLazyStream(GOOGLE_VERTEX_SPECIFIER, "streamSimpleGoogleVertex"),
    });
    // Anthropic Vertex
    registerApiProvider({
        api: "anthropic-vertex",
        stream: createLazyStream(ANTHROPIC_VERTEX_SPECIFIER, "streamAnthropicVertex"),
        streamSimple: createLazyStream(ANTHROPIC_VERTEX_SPECIFIER, "streamSimpleAnthropicVertex"),
    });
    // Amazon Bedrock (uses special override-aware loader)
    registerApiProvider({
        api: "bedrock-converse-stream",
        stream: streamBedrockLazy,
        streamSimple: streamSimpleBedrockLazy,
    });
}
export function resetApiProviders() {
    clearApiProviders();
    clearModuleCache();
    registerBuiltInApiProviders();
}
registerBuiltInApiProviders();
//# sourceMappingURL=register-builtins.js.map