import { registerCodeModeProxyProvider } from "../providers/code-mode-proxy-provider.js";
import { registerOpenAICodexCustomProvider } from "../providers/openai-codex-custom-provider.js";
import { registerCodexCommand } from "../ui/settings/command.js";
import { registerCodexCodeMode } from "../adapter/code-mode.js";
import { registerCodexEvents } from "./events.js";
import { createCodexExtensionRuntime } from "./runtime.js";
import { registerCodexTools } from "./tools.js";
import { registerCodexUi } from "./ui.js";
export async function registerCodexConversion(pi) {
    const runtime = createCodexExtensionRuntime(pi);
    const codeMode = await registerCodexCodeMode(pi, runtime);
    let cleanupProxyProvider;
    try {
        registerOpenAICodexCustomProvider(pi, {
            getConfig: () => ({ openai: runtime.state.config.openai, beta: runtime.state.config.beta }),
            turnState: runtime.state.codexTurnState,
        });
        const proxyProvider = registerCodeModeProxyProvider(pi, () => runtime.state.config);
        cleanupProxyProvider = proxyProvider;
        const tools = registerCodexTools(pi, runtime);
        const ui = registerCodexUi(pi, runtime);
        registerCodexCommand(pi, runtime.state, (config) => {
            proxyProvider.applyConfig(config);
            tools.applyConfig(config);
            ui.applyConfig(config);
        }, { sessions: runtime.sessions, widget: runtime.backgroundWidget });
        registerCodexEvents(pi, runtime, tools, ui, codeMode, proxyProvider);
    }
    catch (registrationError) {
        try {
            try {
                cleanupProxyProvider?.shutdown();
            }
            finally {
                await codeMode.shutdown();
            }
        }
        catch (shutdownError) {
            throw new AggregateError([registrationError, shutdownError], "Codex conversion registration and Code Mode cleanup failed");
        }
        throw registrationError;
    }
}
