/**
 * Shared setup wizard helpers for join/clone commands.
 *
 * Reusable interactive prompts for:
 * - LLM provider configuration
 * - Connector configuration for sync sources
 */
import { confirm, select, password, log, isCancel } from '@clack/prompts';
import { loadUserConfig, saveUserConfig } from '../core/user-config.js';
import { tryResolve } from '../core/secrets/read-flip.js';
export const MODEL_PROVIDERS = {
    anthropic: {
        name: 'Anthropic (Claude)',
        models: [
            { id: 'claude-sonnet-4-6', name: 'Claude Sonnet 4.6', hint: 'Recommended' },
            { id: 'claude-opus-4-7', name: 'Claude Opus 4.7', hint: 'Most capable' },
            { id: 'claude-haiku-4-5-20251001', name: 'Claude Haiku 4.5', hint: 'Fastest' },
        ],
        envVar: 'ANTHROPIC_API_KEY',
    },
    openai: {
        name: 'OpenAI (GPT)',
        models: [
            { id: 'gpt-5.5', name: 'GPT-5.5', hint: 'Recommended (latest GA)' },
            { id: 'gpt-5.5-pro', name: 'GPT-5.5 Pro', hint: 'Most capable' },
            { id: 'gpt-5.4-mini', name: 'GPT-5.4 Mini', hint: 'Fast & cheap' },
        ],
        envVar: 'OPENAI_API_KEY',
    },
    google: {
        name: 'Google (Gemini)',
        models: [
            { id: 'gemini-2.5-pro', name: 'Gemini 2.5 Pro', hint: 'Recommended (GA)' },
            { id: 'gemini-3.1-pro-preview', name: 'Gemini 3.1 Pro Preview', hint: 'Newest (preview — may rotate)' },
            { id: 'gemini-2.5-flash', name: 'Gemini 2.5 Flash', hint: 'Fast & cheap' },
            { id: 'gemini-pro-latest', name: 'Gemini Pro Latest', hint: 'Rolling alias' },
        ],
        envVar: 'GOOGLE_API_KEY',
    },
    // Note: pi-ai and src/core/user-config.ts:createModel also support xai,
    // groq, and openrouter via OpenAI-compatible endpoints. They're not
    // exposed in the wizard until each has been verified end-to-end against
    // the agent's tool-calling + streaming. Set MODEL_PROVIDER=<id> manually
    // to use them in the meantime.
};
/**
 * Prompt for LLM provider setup if not configured.
 * Checks user config and env vars. Skips if already set.
 */
export async function promptLLMSetupIfNeeded() {
    const userConfig = loadUserConfig();
    // Phase 6 read-flip: check the encrypted store first. If the
    // per-provider key is set, treat the model as "already configured"
    // and skip the prompt. We need `model.provider` to know WHICH
    // per-provider slot to read; if provider isn't set, no key is
    // considered configured yet.
    const storeProvider = tryResolve('model.provider');
    if (storeProvider) {
        const storeApiKey = tryResolve(`model.${storeProvider}.api_key`);
        if (storeApiKey) {
            const providerKey = storeProvider;
            const providerLabel = MODEL_PROVIDERS[providerKey]?.name.replace(/\s*\(.*\)/, '') ?? storeProvider;
            log.success(`AI model configured (${providerLabel})`);
            return;
        }
    }
    // Check if already configured via user config
    if (userConfig.api_key) {
        const providerKey = userConfig.model_provider;
        const providerLabel = providerKey
            ? MODEL_PROVIDERS[providerKey]?.name.replace(/\s*\(.*\)/, '') ?? providerKey
            : 'configured';
        log.success(`AI model configured (${providerLabel})`);
        return;
    }
    // Check common per-provider env vars. The generic MODEL_API_KEY env
    // was retired with Phase 12c (2026-05-12) — operators set the
    // provider-specific env directly.
    const envProviders = [
        { key: 'ANTHROPIC_API_KEY', name: 'Anthropic', provider: 'anthropic' },
        { key: 'OPENAI_API_KEY', name: 'OpenAI', provider: 'openai' },
        { key: 'GOOGLE_API_KEY', name: 'Google', provider: 'google' },
        { key: 'XAI_API_KEY', name: 'xAI', provider: 'xai' },
        { key: 'GROQ_API_KEY', name: 'Groq', provider: 'groq' },
        { key: 'OPENROUTER_API_KEY', name: 'OpenRouter', provider: 'openrouter' },
    ];
    for (const { key, name, provider } of envProviders) {
        if (process.env[key]) {
            // Persist the detected provider (and default model) so resolveApiKey() works
            if (!userConfig.model_provider) {
                userConfig.model_provider = provider;
                const defaultModel = MODEL_PROVIDERS[provider]?.models[0]?.id;
                if (defaultModel && !userConfig.model_id) {
                    userConfig.model_id = defaultModel;
                }
                saveUserConfig(userConfig);
            }
            log.success(`AI model configured (${name} via ${key})`);
            return;
        }
    }
    // Skip interactive prompt if no TTY (headless / Railway / CI)
    if (!process.stdout.isTTY) {
        log.info('No AI model configured. Set ANTHROPIC_API_KEY (or another provider env var) and MODEL_PROVIDER environment variables.');
        return;
    }
    // Prompt for setup. The model is required by the agent runtime that
    // runs inside `studiograph serve` (web chat + tool execution); both
    // `serve` and `clone` invoke this wizard.
    const wantSetup = await confirm({
        message: 'Set up an AI model? (required for the agent)',
        initialValue: true,
    });
    if (!wantSetup || typeof wantSetup === 'symbol') {
        log.info('Skipped. Run `studiograph config` later to set up.');
        return;
    }
    const providerChoice = await select({
        message: 'Select AI provider:',
        options: Object.entries(MODEL_PROVIDERS).map(([key, provider]) => ({
            value: key,
            label: provider.name,
        })),
    });
    if (typeof providerChoice === 'symbol') {
        log.info('Skipped. Run `studiograph config` later to set up.');
        return;
    }
    const provider = MODEL_PROVIDERS[providerChoice];
    const modelChoice = await select({
        message: `Select ${provider.name} model:`,
        options: provider.models.map(m => ({
            value: m.id,
            label: m.name,
            hint: m.hint,
        })),
    });
    if (typeof modelChoice === 'symbol') {
        log.info('Skipped. Run `studiograph config` later to set up.');
        return;
    }
    const apiKeyInput = await password({
        message: `Enter your ${provider.name} API key:`,
        validate: (value) => {
            if (!value || value.trim().length < 10)
                return 'API key seems too short';
        },
    });
    if (isCancel(apiKeyInput)) {
        log.info('Skipped. Run `studiograph config` later to set up.');
        return;
    }
    userConfig.model_provider = providerChoice;
    userConfig.model_id = modelChoice;
    userConfig.api_key = apiKeyInput.trim();
    saveUserConfig(userConfig);
    log.success(`AI model configured: ${provider.name} — ${modelChoice}`);
}
/**
 * Detect connectors in the workspace and report missing ones.
 * @deprecated Sync pipeline removed — this is a no-op stub kept for API compat.
 */
export async function promptConnectorSetup(_workspacePath) {
    return 0;
}
//# sourceMappingURL=setup-wizard.js.map