import prompts from "prompts";
import { setProfile, getProfile, loadConfig, saveConfig, configExists, ownerConfigExists, loadOwnerConfig, saveOwnerConfig, } from "./config/index.js";
import { applyGoogleRuntimeCredential } from "./agent/runtime-credentials.js";
import { updateBotName, setProfilePhotoAsync } from "./onboarding/bot-profile.js";
import { setupPlaywrightGmailLogin } from "./onboarding/index.js";
import { getSupportedProvidersForModel } from "./config/types.js";
import { CLAUDE_OPUS_MODEL, CLAUDE_SONNET_MODEL, GPT_MODEL } from "./config/models.js";
import { isPlaywriterExtensionInChromeProfiles, isPlaywriterExtensionJsonInstalled, ensurePlaywriterExtension, } from "./onboarding/playwriter-extension.js";
function getProviderLabel(provider) {
    switch (provider) {
        case "bedrock":
            return "Bedrock";
        case "vertex":
            return "Vertex AI";
        case "9router":
            return "9Router";
        case "openai":
            return "OpenAI";
        case "azure-openai":
            return "Azure OpenAI";
        default:
            return "Anthropic";
    }
}
function getModelLabel(model) {
    switch (model) {
        case "gpt-5.5":
            return "GPT-5.5";
        case "claude-opus-4-8":
            return "Claude Opus 4.8";
        case "claude-opus-4-6":
            return "Claude Opus 4.6";
        default:
            return "Claude Sonnet 4.6";
    }
}
function getProviderChoices(model) {
    return getSupportedProvidersForModel(model).map((provider) => {
        switch (provider) {
            case "bedrock":
                return { title: "Amazon Bedrock (IAM credentials)", value: provider };
            case "vertex":
                return { title: "Google Vertex AI (service account)", value: provider };
            case "9router":
                return { title: "9Router (API-compatible proxy)", value: provider };
            case "openai":
                return { title: "OpenAI (direct API key)", value: provider };
            case "azure-openai":
                return { title: "Azure OpenAI (endpoint + deployment)", value: provider };
            default:
                return { title: "Anthropic (direct API key)", value: provider };
        }
    });
}
function parseProfileFromArgs(args) {
    const idx = args.indexOf("--profile");
    return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : "default";
}
async function refreshGoogleCredentialsFromServer(config) {
    if (!config.onboardingServiceUrl || !config.visionclawServiceApiKey) {
        console.log("\nThis profile is not connected to the onboarding service; cannot refresh server-managed Google credentials.");
        return;
    }
    const baseUrl = config.onboardingServiceUrl.replace(/\/+$/, "");
    const url = `${baseUrl}/api/agents/${encodeURIComponent(config.agentName)}/credentials/google`;
    let response;
    try {
        response = await fetch(url, {
            headers: { Authorization: `Bearer ${config.visionclawServiceApiKey}` },
            signal: AbortSignal.timeout(30_000),
        });
    }
    catch (err) {
        console.log(`\nFailed to reach onboarding service: ${err instanceof Error ? err.message : String(err)}`);
        return;
    }
    if (!response.ok) {
        console.log(`\nFailed to refresh Google credentials from onboarding service: HTTP ${response.status}`);
        return;
    }
    const body = await response.json();
    switch (body.status) {
        case "ready": {
            if (!body.google?.oauthTokensJson || !body.google.password) {
                console.log("\nOnboarding service returned incomplete Google credentials. Re-authorize the profile server-side and retry.");
                return;
            }
            const changed = applyGoogleRuntimeCredential(body.google);
            console.log(changed
                ? "\nGoogle credentials refreshed from onboarding service."
                : "\nGoogle credentials are already up to date.");
            break;
        }
        case "pending_oauth":
            console.log(`\nGoogle Workspace account${body.email ? ` (${body.email})` : ""} is activated, but OAuth tokens are not available on the onboarding server yet. ` +
                "Authorize this profile in the onboarding server profile wizard, then run this command again.");
            break;
        case "not_activated":
            console.log("\nGoogle Workspace is not activated for this profile yet. Complete Google provisioning/activation on the onboarding server first.");
            break;
        case "no_profile":
            console.log("\nThis agent has no allocated profile on the onboarding server. Allocate a profile before refreshing Google credentials.");
            break;
        default:
            console.log("\nOnboarding service returned an unknown Google credential status.");
    }
}
export async function runReconfigureCli(args = process.argv.slice(2)) {
    const profile = parseProfileFromArgs(args);
    setProfile(profile);
    if (!configExists()) {
        console.error(`Profile "${profile}" does not exist. Run 'pnpm dev -- --profile ${profile}' to create it.`);
        process.exit(1);
    }
    const config = loadConfig();
    const hasOwner = ownerConfigExists();
    const ownerConfig = hasOwner ? loadOwnerConfig() : undefined;
    console.log(`\n=== Reconfigure Profile: ${getProfile()} ===`);
    console.log(`Agent: ${config.agentName} <${config.gmail}>\n`);
    const providerLabel = getProviderLabel(config.provider);
    const modelLabel = getModelLabel(config.model);
    const choices = [
        { title: "Update agent name", value: "name" },
        { title: "Update bot identity (Telegram name + profile photo)", value: "bot-identity" },
        { title: "Update Telegram bot token", value: "telegram" },
        { title: "Add/update Discord", value: "discord" },
        { title: `Update API credentials (${providerLabel})`, value: "apikey" },
        { title: `Switch model/provider (current: ${modelLabel} via ${providerLabel})`, value: "provider" },
        { title: "Update SerpApi key", value: "serpapi" },
        { title: "Update Gemini API key", value: "gemini" },
        { title: "Update Phonecall MCP API key", value: "phonecall-mcp" },
        { title: "Update Gmail password", value: "gmail-password" },
        { title: "Update agent phone number", value: "phone" },
        { title: "Update system password", value: "system-password" },
        { title: "Refresh Google credentials from onboarding server", value: "google" },
        { title: "Refresh Playwright Gmail browser login", value: "playwright-gmail" },
        { title: "Reinstall Playwriter Chrome extension", value: "playwriter-extension" },
        { title: "Disable a channel", value: "disable" },
    ];
    if (hasOwner && ownerConfig) {
        choices.splice(3, 0, { title: "Update owner info", value: "owner" }, { title: "Update heartbeat interval", value: "heartbeat" }, { title: "Advanced settings", value: "advanced" });
    }
    const { section } = (await prompts({
        type: "select",
        name: "section",
        message: "What do you want to update?",
        choices,
    }));
    if (!section) {
        return;
    }
    switch (section) {
        case "telegram": {
            const result = (await prompts({
                type: "text",
                name: "botToken",
                message: "Telegram Bot Token:",
                initial: config.channels.telegram?.botToken ?? "",
                validate: (v) => (v.trim().length > 0 ? true : "Required"),
            }));
            if (result.botToken) {
                config.channels.telegram = {
                    enabled: true,
                    botToken: result.botToken,
                };
                saveConfig(config);
                console.log("\nTelegram bot token updated.");
            }
            break;
        }
        case "discord": {
            console.log("\nCreate a bot at https://discord.com/developers/applications");
            console.log("Enable MESSAGE CONTENT intent under Bot settings.\n");
            const result = (await prompts([
                {
                    type: "text",
                    name: "botToken",
                    message: "Discord Bot Token:",
                    initial: config.channels.discord?.botToken ?? "",
                    validate: (v) => (v.trim().length > 0 ? true : "Required"),
                },
                {
                    type: "text",
                    name: "channelId",
                    message: "Discord channel ID (leave blank for DMs only):",
                    initial: ownerConfig?.allowedDiscordChannelIds[0] ?? "",
                },
            ]));
            if (result.botToken) {
                config.channels.discord = {
                    enabled: true,
                    botToken: result.botToken,
                };
                saveConfig(config);
                if (ownerConfig) {
                    ownerConfig.allowedDiscordChannelIds = result.channelId?.trim() ? [result.channelId.trim()] : [];
                    saveOwnerConfig(ownerConfig);
                }
                console.log("\nDiscord configured and enabled.");
            }
            break;
        }
        case "name": {
            const result = (await prompts({
                type: "text",
                name: "agentName",
                message: "Agent name:",
                initial: config.agentName,
            }));
            if (result.agentName) {
                config.agentName = result.agentName;
                saveConfig(config);
                console.log(`\nAgent name updated to "${config.agentName}".`);
            }
            break;
        }
        case "bot-identity": {
            const botToken = config.channels.telegram?.botToken;
            if (!botToken) {
                console.log("\nTelegram bot token is not configured. Please set it first.");
                break;
            }
            const kebabName = config.agentName
                .toLowerCase()
                .replace(/[^a-z0-9]+/g, "-")
                .replace(/^-|-$/g, "");
            const identityResult = (await prompts([
                {
                    type: "text",
                    name: "botName",
                    message: "Bot display name:",
                    initial: config.agentName,
                },
                {
                    type: "text",
                    name: "photoSource",
                    message: "Profile photo (URL or local path):",
                    initial: `https://onboarding.visionclaw.dev/api/agents/${kebabName}/image`,
                },
            ]));
            if (!identityResult.botName && !identityResult.photoSource)
                break;
            if (identityResult.botName) {
                console.log(`\nUpdating bot name to "${identityResult.botName}"…`);
                const nameOk = await updateBotName(botToken, identityResult.botName);
                if (nameOk) {
                    console.log("Bot name updated successfully.");
                }
                else {
                    console.log("Failed to update bot name (see logs above).");
                }
            }
            if (identityResult.photoSource) {
                console.log(`Updating profile photo from: ${identityResult.photoSource}`);
                const photoOk = await setProfilePhotoAsync(botToken, identityResult.photoSource);
                if (photoOk) {
                    console.log("Profile photo updated successfully.");
                }
                else {
                    console.log("Failed to update profile photo (see logs above).");
                }
            }
            break;
        }
        case "owner": {
            if (!ownerConfig)
                break;
            const result = (await prompts([
                {
                    type: "text",
                    name: "ownerName",
                    message: "Owner name:",
                    initial: ownerConfig.ownerName,
                },
                {
                    type: "text",
                    name: "ownerEmail",
                    message: "Owner email:",
                    initial: ownerConfig.ownerEmail,
                },
            ]));
            if (result.ownerName !== undefined) {
                ownerConfig.ownerName = result.ownerName;
                if (result.ownerEmail) {
                    ownerConfig.ownerEmail = result.ownerEmail;
                }
                saveOwnerConfig(ownerConfig);
                console.log("\nOwner info updated.");
            }
            break;
        }
        case "apikey": {
            if (config.provider === "bedrock") {
                const regionResult = (await prompts({
                    type: "text",
                    name: "awsRegion",
                    message: "AWS region:",
                    initial: config.awsRegion ?? "us-west-2",
                    validate: (v) => (v.trim().length > 0 ? true : "Required"),
                }));
                const bearerResult = (await prompts({
                    type: "text",
                    name: "awsBearerToken",
                    message: "Bedrock bearer token (AWS_BEARER_TOKEN_BEDROCK):",
                    initial: config.awsBearerToken ?? "",
                    validate: (v) => (v.trim().length > 0 ? true : "Required"),
                }));
                const accessKeyResult = (await prompts({
                    type: "text",
                    name: "awsAccessKeyId",
                    message: "AWS Access Key ID:",
                    initial: config.awsAccessKeyId ?? "",
                    validate: (v) => (v.trim().length > 0 ? true : "Required"),
                }));
                const secretKeyResult = (await prompts({
                    type: "text",
                    name: "awsSecretAccessKey",
                    message: "AWS Secret Access Key:",
                    initial: config.awsSecretAccessKey ?? "",
                    validate: (v) => (v.trim().length > 0 ? true : "Required"),
                }));
                const sessionTokenResult = (await prompts({
                    type: "text",
                    name: "awsSessionToken",
                    message: "AWS Session Token (optional, press Enter to skip):",
                    initial: config.awsSessionToken ?? "",
                }));
                if (regionResult.awsRegion)
                    config.awsRegion = regionResult.awsRegion;
                if (bearerResult.awsBearerToken)
                    config.awsBearerToken = bearerResult.awsBearerToken;
                if (accessKeyResult.awsAccessKeyId)
                    config.awsAccessKeyId = accessKeyResult.awsAccessKeyId;
                if (secretKeyResult.awsSecretAccessKey)
                    config.awsSecretAccessKey = secretKeyResult.awsSecretAccessKey;
                config.awsSessionToken = sessionTokenResult.awsSessionToken?.trim() ? sessionTokenResult.awsSessionToken.trim() : undefined;
                if (regionResult.awsRegion || bearerResult.awsBearerToken || accessKeyResult.awsAccessKeyId) {
                    saveConfig(config);
                    console.log("\nBedrock credentials updated.");
                }
            }
            else if (config.provider === "vertex") {
                const projectIdResult = (await prompts({
                    type: "text",
                    name: "vertexProjectId",
                    message: "Google Cloud project ID:",
                    initial: config.vertexProjectId ?? "",
                    validate: (v) => (v.trim().length > 0 ? true : "Required"),
                }));
                const regionResult = (await prompts({
                    type: "text",
                    name: "vertexRegion",
                    message: "Vertex AI region:",
                    initial: config.vertexRegion,
                    validate: (v) => (v.trim().length > 0 ? true : "Required"),
                }));
                const credentialsResult = (await prompts({
                    type: "text",
                    name: "googleApplicationCredentials",
                    message: "Path to service account JSON (GOOGLE_APPLICATION_CREDENTIALS):",
                    initial: config.googleApplicationCredentials ?? "",
                    validate: (v) => (v.trim().length > 0 ? true : "Required"),
                }));
                if (projectIdResult.vertexProjectId)
                    config.vertexProjectId = projectIdResult.vertexProjectId;
                if (regionResult.vertexRegion)
                    config.vertexRegion = regionResult.vertexRegion;
                if (credentialsResult.googleApplicationCredentials)
                    config.googleApplicationCredentials = credentialsResult.googleApplicationCredentials;
                if (projectIdResult.vertexProjectId || regionResult.vertexRegion || credentialsResult.googleApplicationCredentials) {
                    saveConfig(config);
                    console.log("\nVertex AI credentials updated.");
                }
            }
            else if (config.provider === "openai") {
                const result = (await prompts({
                    type: "text",
                    name: "apiKey",
                    message: "OpenAI API key:",
                    initial: config.openaiApiKey ?? "",
                    validate: (v) => (v.trim().length > 0 ? true : "Required"),
                }));
                if (result.apiKey) {
                    config.openaiApiKey = result.apiKey;
                    saveConfig(config);
                    console.log("\nAPI key updated.");
                }
            }
            else if (config.provider === "azure-openai") {
                const result = (await prompts([
                    {
                        type: "text",
                        name: "endpoint",
                        message: "Azure OpenAI endpoint:",
                        initial: config.azureOpenAIEndpoint ?? "",
                        validate: (v) => (v.trim().length > 0 ? true : "Required"),
                    },
                    {
                        type: "text",
                        name: "apiKey",
                        message: "Azure OpenAI API key:",
                        initial: config.azureOpenAIApiKey ?? "",
                        validate: (v) => (v.trim().length > 0 ? true : "Required"),
                    },
                    {
                        type: "text",
                        name: "deployment",
                        message: "Azure OpenAI deployment name:",
                        initial: config.azureOpenAIDeployment ?? "",
                        validate: (v) => (v.trim().length > 0 ? true : "Required"),
                    },
                    {
                        type: "text",
                        name: "apiVersion",
                        message: "Azure OpenAI API version:",
                        initial: config.azureOpenAIApiVersion ?? "preview",
                        validate: (v) => (v.trim().length > 0 ? true : "Required"),
                    },
                ]));
                if (result.endpoint)
                    config.azureOpenAIEndpoint = result.endpoint;
                if (result.apiKey)
                    config.azureOpenAIApiKey = result.apiKey;
                if (result.deployment)
                    config.azureOpenAIDeployment = result.deployment;
                if (result.apiVersion)
                    config.azureOpenAIApiVersion = result.apiVersion;
                if (result.endpoint || result.apiKey || result.deployment || result.apiVersion) {
                    saveConfig(config);
                    console.log("\nAzure OpenAI credentials updated.");
                }
            }
            else if (config.provider === "9router") {
                const result = (await prompts([
                    {
                        type: "text",
                        name: "baseUrl",
                        message: "9Router base URL:",
                        initial: config.ninerouterBaseUrl,
                        validate: (v) => (v.trim().length > 0 ? true : "Required"),
                    },
                    {
                        type: "text",
                        name: "apiKey",
                        message: "9Router API key (leave blank if not required):",
                        initial: config.ninerouterApiKey ?? "",
                    },
                ]));
                if (result.baseUrl)
                    config.ninerouterBaseUrl = result.baseUrl;
                config.ninerouterApiKey = result.apiKey?.trim() ? result.apiKey.trim() : undefined;
                if (result.baseUrl || result.apiKey !== undefined) {
                    saveConfig(config);
                    console.log("\n9Router credentials updated.");
                }
            }
            else {
                const result = (await prompts({
                    type: "text",
                    name: "apiKey",
                    message: "Anthropic API key:",
                    initial: config.anthropicApiKey ?? "",
                    validate: (v) => (v.trim().length > 0 ? true : "Required"),
                }));
                if (result.apiKey) {
                    config.anthropicApiKey = result.apiKey;
                    saveConfig(config);
                    console.log("\nAPI key updated.");
                }
            }
            break;
        }
        case "provider": {
            const modelResult = (await prompts({
                type: "select",
                name: "model",
                message: "AI model:",
                choices: [
                    { title: "Claude Opus 4.8", value: CLAUDE_OPUS_MODEL },
                    { title: "Claude Sonnet 4.6", value: CLAUDE_SONNET_MODEL },
                    { title: "GPT-5.5", value: GPT_MODEL },
                ],
                initial: config.model === GPT_MODEL ? 2 : config.model === CLAUDE_SONNET_MODEL ? 1 : 0,
            }));
            const nextModel = modelResult.model ?? config.model;
            const providerChoices = getProviderChoices(nextModel);
            const providerResult = (await prompts({
                type: "select",
                name: "provider",
                message: "AI provider:",
                choices: providerChoices,
                initial: Math.max(0, providerChoices.findIndex((choice) => choice.value === config.provider)),
            }));
            const nextProvider = providerResult.provider
                ?? providerChoices.find((choice) => choice.value === config.provider)?.value
                ?? providerChoices[0].value;
            if (nextProvider !== config.provider || nextModel !== config.model) {
                config.model = nextModel;
                config.provider = nextProvider;
                if (nextProvider === "bedrock") {
                    const regionResult = (await prompts({
                        type: "text",
                        name: "awsRegion",
                        message: "AWS region:",
                        initial: config.awsRegion ?? "us-west-2",
                        validate: (v) => (v.trim().length > 0 ? true : "Required"),
                    }));
                    if (regionResult.awsRegion)
                        config.awsRegion = regionResult.awsRegion;
                    const bearerResult = (await prompts({
                        type: "text",
                        name: "awsBearerToken",
                        message: "Bedrock bearer token (AWS_BEARER_TOKEN_BEDROCK):",
                        initial: config.awsBearerToken ?? "",
                        validate: (v) => (v.trim().length > 0 ? true : "Required"),
                    }));
                    if (bearerResult.awsBearerToken)
                        config.awsBearerToken = bearerResult.awsBearerToken;
                    const accessKeyResult = (await prompts({
                        type: "text",
                        name: "awsAccessKeyId",
                        message: "AWS Access Key ID:",
                        initial: config.awsAccessKeyId ?? "",
                        validate: (v) => (v.trim().length > 0 ? true : "Required"),
                    }));
                    if (accessKeyResult.awsAccessKeyId)
                        config.awsAccessKeyId = accessKeyResult.awsAccessKeyId;
                    const secretKeyResult = (await prompts({
                        type: "text",
                        name: "awsSecretAccessKey",
                        message: "AWS Secret Access Key:",
                        initial: config.awsSecretAccessKey ?? "",
                        validate: (v) => (v.trim().length > 0 ? true : "Required"),
                    }));
                    if (secretKeyResult.awsSecretAccessKey)
                        config.awsSecretAccessKey = secretKeyResult.awsSecretAccessKey;
                    const sessionTokenResult = (await prompts({
                        type: "text",
                        name: "awsSessionToken",
                        message: "AWS Session Token (optional, press Enter to skip):",
                        initial: config.awsSessionToken ?? "",
                    }));
                    config.awsSessionToken = sessionTokenResult.awsSessionToken?.trim() ? sessionTokenResult.awsSessionToken.trim() : undefined;
                }
                else if (nextProvider === "vertex") {
                    const projectIdResult = (await prompts({
                        type: "text",
                        name: "vertexProjectId",
                        message: "Google Cloud project ID:",
                        initial: config.vertexProjectId ?? "",
                        validate: (v) => (v.trim().length > 0 ? true : "Required"),
                    }));
                    if (projectIdResult.vertexProjectId)
                        config.vertexProjectId = projectIdResult.vertexProjectId;
                    const regionResult = (await prompts({
                        type: "text",
                        name: "vertexRegion",
                        message: "Vertex AI region:",
                        initial: config.vertexRegion,
                        validate: (v) => (v.trim().length > 0 ? true : "Required"),
                    }));
                    if (regionResult.vertexRegion)
                        config.vertexRegion = regionResult.vertexRegion;
                    const credentialsResult = (await prompts({
                        type: "text",
                        name: "googleApplicationCredentials",
                        message: "Path to service account JSON (GOOGLE_APPLICATION_CREDENTIALS):",
                        initial: config.googleApplicationCredentials ?? "",
                        validate: (v) => (v.trim().length > 0 ? true : "Required"),
                    }));
                    if (credentialsResult.googleApplicationCredentials)
                        config.googleApplicationCredentials = credentialsResult.googleApplicationCredentials;
                }
                else if (nextProvider === "9router") {
                    const routerResult = (await prompts([
                        {
                            type: "text",
                            name: "baseUrl",
                            message: "9Router base URL:",
                            initial: config.ninerouterBaseUrl,
                            validate: (v) => (v.trim().length > 0 ? true : "Required"),
                        },
                        {
                            type: "text",
                            name: "apiKey",
                            message: "9Router API key (leave blank if not required):",
                            initial: config.ninerouterApiKey ?? "",
                        },
                    ]));
                    if (routerResult.baseUrl)
                        config.ninerouterBaseUrl = routerResult.baseUrl;
                    config.ninerouterApiKey = routerResult.apiKey?.trim() ? routerResult.apiKey.trim() : undefined;
                }
                else if (nextProvider === "openai") {
                    const keyResult = (await prompts({
                        type: "text",
                        name: "apiKey",
                        message: "OpenAI API key:",
                        initial: config.openaiApiKey ?? "",
                        validate: (v) => (v.trim().length > 0 ? true : "Required"),
                    }));
                    if (keyResult.apiKey)
                        config.openaiApiKey = keyResult.apiKey;
                }
                else if (nextProvider === "azure-openai") {
                    const azureResult = (await prompts([
                        {
                            type: "text",
                            name: "endpoint",
                            message: "Azure OpenAI endpoint:",
                            initial: config.azureOpenAIEndpoint ?? "",
                            validate: (v) => (v.trim().length > 0 ? true : "Required"),
                        },
                        {
                            type: "text",
                            name: "apiKey",
                            message: "Azure OpenAI API key:",
                            initial: config.azureOpenAIApiKey ?? "",
                            validate: (v) => (v.trim().length > 0 ? true : "Required"),
                        },
                        {
                            type: "text",
                            name: "deployment",
                            message: "Azure OpenAI deployment name:",
                            initial: config.azureOpenAIDeployment ?? "",
                            validate: (v) => (v.trim().length > 0 ? true : "Required"),
                        },
                        {
                            type: "text",
                            name: "apiVersion",
                            message: "Azure OpenAI API version:",
                            initial: config.azureOpenAIApiVersion ?? "preview",
                            validate: (v) => (v.trim().length > 0 ? true : "Required"),
                        },
                    ]));
                    if (azureResult.endpoint)
                        config.azureOpenAIEndpoint = azureResult.endpoint;
                    if (azureResult.apiKey)
                        config.azureOpenAIApiKey = azureResult.apiKey;
                    if (azureResult.deployment)
                        config.azureOpenAIDeployment = azureResult.deployment;
                    if (azureResult.apiVersion)
                        config.azureOpenAIApiVersion = azureResult.apiVersion;
                }
                else {
                    const keyResult = (await prompts({
                        type: "text",
                        name: "apiKey",
                        message: "Anthropic API key:",
                        initial: config.anthropicApiKey ?? "",
                        validate: (v) => (v.trim().length > 0 ? true : "Required"),
                    }));
                    if (keyResult.apiKey)
                        config.anthropicApiKey = keyResult.apiKey;
                }
                saveConfig(config);
                console.log(`\nSwitched to ${getModelLabel(nextModel)} via ${getProviderLabel(nextProvider)}.`);
            }
            break;
        }
        case "serpapi": {
            const result = (await prompts({
                type: "text",
                name: "serpApiKey",
                message: "SerpApi key (leave blank to remove):",
                initial: config.serpApiKey ?? "",
            }));
            if (result.serpApiKey !== undefined) {
                config.serpApiKey = result.serpApiKey.trim() ? result.serpApiKey.trim() : undefined;
                saveConfig(config);
                console.log(config.serpApiKey ? "\nSerpApi key updated." : "\nSerpApi key removed.");
            }
            break;
        }
        case "gemini": {
            const result = (await prompts({
                type: "text",
                name: "geminiApiKey",
                message: "Gemini API key (leave blank to use shared key from onboarding service):",
                initial: config.geminiApiKey ?? "",
            }));
            if (result.geminiApiKey !== undefined) {
                config.geminiApiKey = result.geminiApiKey.trim() ? result.geminiApiKey.trim() : undefined;
                saveConfig(config);
                console.log(config.geminiApiKey
                    ? "\nGemini API key updated."
                    : "\nGemini API key removed (will use shared key from onboarding service if available).");
            }
            break;
        }
        case "phonecall-mcp": {
            const result = (await prompts({
                type: "text",
                name: "phonecallApiKey",
                message: "Phonecall MCP API key (leave blank to use shared key from onboarding service):",
                initial: config.phonecallApiKey ?? "",
            }));
            if (result.phonecallApiKey !== undefined) {
                config.phonecallApiKey = result.phonecallApiKey.trim() ? result.phonecallApiKey.trim() : undefined;
                saveConfig(config);
                console.log(config.phonecallApiKey
                    ? "\nPhonecall MCP API key updated."
                    : "\nPhonecall MCP API key removed (will use shared key from onboarding service if available).");
            }
            break;
        }
        case "gmail-password": {
            const result = (await prompts({
                type: "password",
                name: "gmailPassword",
                message: "Gmail password (leave blank to remove):",
            }));
            if (result.gmailPassword !== undefined) {
                config.gmailPassword = result.gmailPassword.trim() ? result.gmailPassword.trim() : undefined;
                saveConfig(config);
                console.log(config.gmailPassword ? "\nGmail password updated." : "\nGmail password removed.");
            }
            break;
        }
        case "phone": {
            const result = (await prompts({
                type: "text",
                name: "phoneNumber",
                message: "Agent phone number (leave blank to remove):",
                initial: config.phoneNumber ?? "",
            }));
            if (result.phoneNumber !== undefined) {
                config.phoneNumber = result.phoneNumber.trim() ? result.phoneNumber.trim() : undefined;
                saveConfig(config);
                console.log(config.phoneNumber ? "\nAgent phone number updated." : "\nAgent phone number removed.");
            }
            break;
        }
        case "system-password": {
            const result = (await prompts({
                type: "password",
                name: "systemPassword",
                message: "System password (leave blank to remove):",
            }));
            if (result.systemPassword !== undefined) {
                config.systemPassword = result.systemPassword.trim() ? result.systemPassword.trim() : undefined;
                saveConfig(config);
                console.log(config.systemPassword ? "\nSystem password updated." : "\nSystem password removed.");
            }
            break;
        }
        case "google": {
            await refreshGoogleCredentialsFromServer(config);
            break;
        }
        case "playwright-gmail": {
            await setupPlaywrightGmailLogin(config.gmail);
            break;
        }
        case "playwriter-extension": {
            if (process.platform !== "darwin") {
                console.log("\nPlaywriter extension installation is only supported on macOS.");
                break;
            }
            if (isPlaywriterExtensionJsonInstalled()) {
                const extStatus = isPlaywriterExtensionInChromeProfiles();
                if (extStatus.installed) {
                    console.log(`\nPlaywriter extension already installed in: ${extStatus.profiles.join(", ")}`);
                }
                else {
                    console.log("\nPlaywriter External Extensions JSON is configured.");
                    console.log("Restart Chrome for the extension to install automatically.");
                }
                const reinstall = (await prompts({
                    type: "confirm",
                    name: "proceed",
                    message: "Rewrite configuration anyway?",
                    initial: false,
                }));
                if (!reinstall.proceed)
                    break;
            }
            const ok = ensurePlaywriterExtension();
            if (ok) {
                console.log("\nPlaywriter External Extensions JSON written successfully.");
                console.log("Restart Chrome for the extension to be installed automatically.");
            }
            else {
                console.log("\nFailed to write Playwriter External Extensions JSON.");
            }
            break;
        }
        case "heartbeat": {
            if (!ownerConfig)
                break;
            const result = (await prompts({
                type: "number",
                name: "seconds",
                message: "Heartbeat interval (seconds):",
                initial: ownerConfig.heartbeatIntervalMs / 1000,
                min: 30,
            }));
            if (result.seconds) {
                ownerConfig.heartbeatIntervalMs = result.seconds * 1000;
                saveOwnerConfig(ownerConfig);
                console.log(`\nHeartbeat interval updated to ${result.seconds}s.`);
            }
            break;
        }
        case "advanced": {
            if (!ownerConfig)
                break;
            const currentStatus = ownerConfig.dualSessionEnabled ? "enabled" : "disabled";
            const result = (await prompts({
                type: "select",
                name: "advancedSetting",
                message: "Advanced settings",
                choices: [
                    {
                        title: `Dual-session mode (${currentStatus})`,
                        value: "dual-session",
                    },
                ],
            }));
            if (result.advancedSetting !== "dual-session") {
                break;
            }
            const toggleResult = (await prompts({
                type: "confirm",
                name: "enabled",
                message: "Enable dual-session mode? This is an advanced option for sustained coding workflows and adds extra runtime complexity.",
                initial: ownerConfig.dualSessionEnabled,
            }));
            if (toggleResult.enabled !== undefined) {
                ownerConfig.dualSessionEnabled = toggleResult.enabled;
                saveOwnerConfig(ownerConfig);
                console.log(`\nDual-session mode ${toggleResult.enabled ? "enabled" : "disabled"}.`);
            }
            break;
        }
        case "disable": {
            const enabled = [];
            if (config.channels.telegram?.enabled)
                enabled.push({ title: "Telegram", value: "telegram" });
            if (config.channels.discord?.enabled)
                enabled.push({ title: "Discord", value: "discord" });
            if (enabled.length === 0) {
                console.log("\nNo channels to disable (Gmail is always on).");
                break;
            }
            const result = (await prompts({
                type: "select",
                name: "channel",
                message: "Which channel to disable?",
                choices: enabled,
            }));
            if (result.channel === "telegram" && config.channels.telegram) {
                config.channels.telegram.enabled = false;
            }
            else if (result.channel === "discord" && config.channels.discord) {
                config.channels.discord.enabled = false;
            }
            if (result.channel) {
                saveConfig(config);
                console.log(`\n${result.channel} disabled.`);
            }
            break;
        }
    }
    console.log("");
}
//# sourceMappingURL=reconfigure.js.map