import { normalizeCodexVerbosity, readCodexConversionConfig, writeCodexConversionConfig, } from "../../adapter/activation/config.js";
import { syncAdapter } from "../../adapter/activation/activation.js";
import { openCodexSettingsScreen } from "./ui.js";
import { consumeCodexRateLimitResetCredit, fetchCodexUsage, formatCodexUsage } from "./usage.js";
import { renderBackgroundBashWidget } from "../background-bash-widget.js";
const CODEX_COMMAND_COMPLETIONS = ["all", "status", "fast", "compact", "usage", "reset", "ps", "low", "medium", "high"];
const CODEX_USAGE = "Usage: /codex, /codex all, /codex status, /codex fast, /codex compact, /codex usage, /codex reset, /codex ps, /codex low|medium|high";
export function registerCodexCommand(pi, state, onConfigApplied, backgroundShells) {
    function saveAndApply(ctx, nextConfig) {
        const writeResult = writeCodexConversionConfig(nextConfig);
        if (!writeResult.ok) {
            ctx.ui.notify(`Failed to save Codex settings: ${writeResult.error}`, "error");
            return false;
        }
        state.config = nextConfig;
        onConfigApplied?.(nextConfig);
        syncAdapter(pi, ctx, state);
        return true;
    }
    pi.registerCommand("codex", {
        description: "Configure Codex adapter settings",
        getArgumentCompletions: (prefix) => CODEX_COMMAND_COMPLETIONS.filter((item) => item.startsWith(prefix.trim().toLowerCase())).map((value) => ({ label: value, value })),
        handler: async (args, ctx) => {
            state.config = readCodexConversionConfig();
            const arg = args.trim().toLowerCase();
            if (arg === "ps") {
                if (!state.config.ui.backgroundShellWidget) {
                    ctx.ui.notify("Background shells widget is off.", "info");
                    return;
                }
                if (!backgroundShells || backgroundShells.sessions.listSessions().length === 0) {
                    ctx.ui.notify("No background shells running.", "info");
                    return;
                }
                backgroundShells.widget.ctx = ctx;
                backgroundShells.widget.folded = false;
                renderBackgroundBashWidget(ctx, backgroundShells.widget, backgroundShells.sessions);
                return;
            }
            if (arg === "usage" || arg === "reset") {
                let usage;
                try {
                    usage = await fetchCodexUsage(ctx);
                }
                catch (error) {
                    const message = error instanceof Error ? error.message : String(error);
                    if (!ctx.hasUI) {
                        ctx.ui.notify(message, "error");
                        return;
                    }
                    await openCodexSettingsScreen(ctx, {
                        initialConfig: state.config,
                        initialTab: "usage",
                        initialUsage: { error: message },
                        onChange: (config) => saveAndApply(ctx, config),
                    });
                    return;
                }
                if (!ctx.hasUI) {
                    ctx.ui.notify(formatCodexUsage(usage), "info");
                    return;
                }
                await openCodexSettingsScreen(ctx, {
                    initialConfig: state.config,
                    initialTab: "usage",
                    initialUsage: usage,
                    onConsumeResetCredit: (redeemRequestId) => consumeCodexRateLimitResetCredit(ctx, redeemRequestId),
                    onChange: (config) => saveAndApply(ctx, config),
                });
                return;
            }
            if (arg === "compact") {
                if (!ctx.hasUI) {
                    ctx.ui.notify(formatCodexSettings(state.config), "info");
                    return;
                }
                await openCodexSettingsScreen(ctx, {
                    initialConfig: state.config,
                    initialTab: "openai",
                    onChange: (config) => saveAndApply(ctx, config),
                });
                return;
            }
            const nextConfig = getCommandConfigUpdate(arg, state.config);
            if (nextConfig) {
                saveAndApply(ctx, nextConfig);
                return;
            }
            if (arg) {
                ctx.ui.notify(CODEX_USAGE, "warning");
                return;
            }
            if (!ctx.hasUI) {
                ctx.ui.notify(formatCodexSettings(state.config), "info");
                return;
            }
            await openCodexSettingsScreen(ctx, {
                initialConfig: state.config,
                onChange: (config) => saveAndApply(ctx, config),
            });
        },
    });
}
function getCommandConfigUpdate(arg, config) {
    if (arg === "fast")
        return { ...config, openai: { ...config.openai, fast: !config.openai.fast } };
    if (arg === "all")
        return { ...config, scope: { ...config.scope, allProviders: nextAllProvidersMode(config.scope.allProviders) } };
    if (arg === "status")
        return { ...config, ui: { ...config.ui, statusLine: !config.ui.statusLine } };
    const verbosity = normalizeCodexVerbosity(arg);
    return verbosity ? { ...config, openai: { ...config.openai, verbosity } } : undefined;
}
function nextAllProvidersMode(value) {
    if (value === "off")
        return "on";
    if (value === "on")
        return "extras";
    return "off";
}
function formatAllProvidersMode(value) {
    return value === "extras" ? "only extras" : value;
}
function formatCodexSettings(config) {
    const extraTools = [
        config.tools.applyPatchOnly ? "apply_patch" : undefined,
        config.tools.viewImageOnly ? "view_image" : undefined,
        config.tools.webRunOnly ? "web_run" : undefined,
        config.tools.imageGenerationOnly ? "imagegen" : undefined,
    ].filter(Boolean).join(", ") || "off";
    return `Codex settings: all models ${formatAllProvidersMode(config.scope.allProviders)}, additional providers ${config.scope.additionalProviders.length > 0 ? config.scope.additionalProviders.join(", ") : "none"}, statusline ${config.ui.statusLine ? "on" : "off"}, tool renaming ${config.ui.toolRenaming ? "on" : "off"}, compact tools ${config.ui.compactTools ? "on" : "off"}, Code Mode details ${config.ui.codeModeDetails ? "on" : "off"}, background shells widget ${config.ui.backgroundShellWidget ? "on" : "off"}, image descriptions ${config.tools.viewImageFallback ? "on" : "off"}, extra tools only ${extraTools}, fast ${config.openai.fast ? "on" : "off"}, cached websocket upgrade ${config.openai.forceCachedWebSockets === false ? "off" : "on"}, GPT-5.6 Code Mode ${config.beta.codeMode ? "on" : "off"}, proxy Responses Lite ${config.beta.responsesLite ? "on" : "off"}, responses compaction ${(config.compaction.responsesCompaction ?? false) ? "on" : "off"} (${config.openai.compactionModel}/${config.openai.compactionReasoning}), verbosity ${config.openai.verbosity}`;
}
