/**
 * cv init command
 * Initialize CV-Git in a repository or workspace
 */
import { Command } from 'commander';
import chalk from 'chalk';
import * as path from 'path';
import inquirer from 'inquirer';
import { configManager } from '@cv-git/core';
import { ensureDir, getCVDir, detectProjectType, saveWorkspace, isWorkspace, generateDatabaseName, } from '@cv-git/shared';
import { CredentialManager } from '@cv-git/credentials';
import { addGlobalOptions, createOutput } from '../utils/output.js';
import { getPreferences } from '../config.js';
import { runPreferencePicker, displayPreferenceSummary, savePreferences, getRequiredServices, } from '../utils/preference-picker.js';
export function initCommand() {
    const cmd = new Command('init');
    cmd
        .description('Initialize CV-Git in the current repository or workspace')
        .option('--name <name>', 'Repository/workspace name (defaults to directory name)')
        .option('--workspace', 'Force workspace mode (multi-repo)')
        .option('--repo', 'Force single-repo mode')
        .option('--skip-preferences', 'Skip preference picker (for developers testing all providers)')
        .option('-y, --yes', 'Non-interactive mode with defaults (for AI/automation)')
        .option('--platform <platform>', 'Git platform: github, gitlab, bitbucket (default: github)')
        .option('--ai-provider <provider>', 'AI provider: anthropic, openai, openrouter (default: anthropic)')
        .option('--embedding-provider <provider>', 'Embedding provider: openai, openrouter (default: openrouter)');
    addGlobalOptions(cmd);
    cmd.action(async (options) => {
        const output = createOutput(options);
        try {
            const currentDir = process.cwd();
            const projectName = options.name || path.basename(currentDir);
            const prefsManager = getPreferences();
            // Check if preferences already exist (returning user)
            const hasPrefs = await prefsManager.exists();
            let preferences;
            const skipPrefs = options.skipPreferences === true;
            // Non-interactive mode: -y/--yes, --json, or --skip-preferences
            const nonInteractive = options.yes || output.isJson || skipPrefs;
            if (nonInteractive) {
                // Non-interactive mode - use defaults or explicit options
                if (!output.isJson && !skipPrefs) {
                    console.log(chalk.gray('Running in non-interactive mode with defaults'));
                    console.log();
                }
                else if (skipPrefs) {
                    console.log(chalk.gray('Skipping preferences (developer mode)'));
                    console.log();
                }
                preferences = {
                    gitPlatform: (options.platform || 'github'),
                    aiProvider: (options.aiProvider || 'anthropic'),
                    embeddingProvider: (options.embeddingProvider || 'openrouter'),
                };
                // Save preferences in non-interactive mode too
                if (!hasPrefs) {
                    await savePreferences(preferences);
                }
            }
            else if (!hasPrefs) {
                // First-time setup - run preference picker
                preferences = await runPreferencePicker();
                displayPreferenceSummary(preferences);
                // Confirm preferences
                const { confirmPrefs } = await inquirer.prompt([
                    {
                        type: 'confirm',
                        name: 'confirmPrefs',
                        message: 'Continue with these preferences?',
                        default: true,
                    },
                ]);
                if (!confirmPrefs) {
                    // Let them re-pick
                    preferences = await runPreferencePicker(preferences);
                    displayPreferenceSummary(preferences);
                }
                // Save preferences
                await savePreferences(preferences);
                console.log(chalk.green('Preferences saved!'));
                console.log();
            }
            else {
                // Load existing preferences
                const existingPrefs = await prefsManager.load();
                preferences = {
                    gitPlatform: existingPrefs.gitPlatform,
                    aiProvider: existingPrefs.aiProvider,
                    embeddingProvider: existingPrefs.embeddingProvider,
                };
            }
            const spinner = output.spinner('Detecting project type...').start();
            // Detect project type
            const detected = await detectProjectType(currentDir);
            // Check if already initialized
            const cvDir = getCVDir(currentDir);
            if (await isWorkspace(currentDir)) {
                spinner.warn(chalk.yellow('CV-Git workspace already initialized in this directory'));
                return;
            }
            try {
                await configManager.load(currentDir);
                spinner.warn(chalk.yellow('CV-Git is already initialized in this directory'));
                return;
            }
            catch {
                // Not initialized, proceed
            }
            // Determine mode based on detection and options
            let mode;
            if (options.workspace) {
                mode = 'workspace';
            }
            else if (options.repo) {
                mode = 'repo';
            }
            else if (detected.type === 'workspace' && detected.childRepos && detected.childRepos.length > 0) {
                // Found child git repos
                if (nonInteractive) {
                    // In non-interactive mode, default to workspace mode
                    mode = 'workspace';
                    spinner.text = 'Initializing CV-Git workspace (non-interactive)...';
                }
                else {
                    // Ask user
                    spinner.stop();
                    console.log();
                    console.log(chalk.cyan(`Found ${detected.childRepos.length} git repositories in this directory:`));
                    for (const repo of detected.childRepos) {
                        console.log(chalk.gray(`  - ${repo.name}/`));
                    }
                    console.log();
                    const { initMode } = await inquirer.prompt([
                        {
                            type: 'list',
                            name: 'initMode',
                            message: 'How would you like to initialize CV-Git?',
                            choices: [
                                {
                                    name: `Workspace mode - Create unified index across all ${detected.childRepos.length} repos`,
                                    value: 'workspace',
                                },
                                {
                                    name: 'Skip - Initialize individual repos separately',
                                    value: 'skip',
                                },
                            ],
                        },
                    ]);
                    if (initMode === 'skip') {
                        console.log(chalk.gray('\nTo initialize a single repo, cd into it and run `cv init`'));
                        return;
                    }
                    mode = initMode;
                    spinner.start('Initializing CV-Git workspace...');
                }
            }
            else if (detected.type === 'repo') {
                mode = 'repo';
            }
            else {
                // Not a git repo - offer to initialize one
                spinner.stop();
                console.log();
                console.log(chalk.yellow('This directory is not a git repository.'));
                console.log();
                if (options.yes) {
                    // Non-interactive mode: auto-init git
                    console.log(chalk.cyan('Initializing git repository...'));
                    const { execSync } = await import('child_process');
                    const { writeFileSync, existsSync } = await import('fs');
                    execSync('git init -b main', { cwd: currentDir, stdio: 'inherit' });
                    // Create initial commit so git commands work
                    const readmePath = path.join(currentDir, 'README.md');
                    if (!existsSync(readmePath)) {
                        writeFileSync(readmePath, `# ${projectName}\n\nInitialized with CV-Git.\n`);
                    }
                    execSync('git add -A && git commit -m "Initial commit"', { cwd: currentDir, stdio: 'inherit', shell: '/bin/bash' });
                    mode = 'repo';
                    spinner.start('Initializing CV-Git...');
                }
                else {
                    const { initGit } = await inquirer.prompt([
                        {
                            type: 'confirm',
                            name: 'initGit',
                            message: 'Would you like to initialize a git repository here?',
                            default: true,
                        },
                    ]);
                    if (initGit) {
                        console.log();
                        console.log(chalk.cyan('Initializing git repository...'));
                        const { execSync } = await import('child_process');
                        const { writeFileSync, existsSync } = await import('fs');
                        execSync('git init -b main', { cwd: currentDir, stdio: 'inherit' });
                        // Create initial commit so git commands work
                        const readmePath = path.join(currentDir, 'README.md');
                        if (!existsSync(readmePath)) {
                            writeFileSync(readmePath, `# ${projectName}\n\nInitialized with CV-Git.\n`);
                        }
                        execSync('git add -A && git commit -m "Initial commit"', { cwd: currentDir, stdio: 'inherit', shell: '/bin/bash' });
                        mode = 'repo';
                        spinner.start('Initializing CV-Git...');
                    }
                    else {
                        console.log(chalk.gray('\nRun `cv init` inside a git repository, or in a folder containing git repos.'));
                        process.exit(1);
                    }
                }
            }
            // Create .cv directory
            spinner.text = 'Creating .cv directory...';
            await ensureDir(cvDir);
            await ensureDir(path.join(cvDir, 'cache'));
            await ensureDir(path.join(cvDir, 'sessions'));
            if (mode === 'workspace') {
                // Initialize workspace mode
                await initWorkspace(currentDir, projectName, detected.childRepos || [], spinner, output);
            }
            else {
                // Initialize single repo mode
                await initSingleRepo(currentDir, projectName, spinner, output);
            }
            spinner.succeed(`CV-Git ${mode === 'workspace' ? 'workspace' : 'repository'} initialized successfully!`);
            if (output.isJson) {
                output.json({ success: true, name: projectName, cvDir, mode, preferences });
            }
            else {
                console.log();
                // Check which global credentials exist for the selected preferences
                const requiredServices = getRequiredServices(preferences);
                const credentialStatus = await checkGlobalCredentials(requiredServices);
                if (credentialStatus.configured.length > 0) {
                    console.log(chalk.bold('Using credentials:'));
                    for (const svc of credentialStatus.configured) {
                        console.log(chalk.green(`  ✓ ${svc}`));
                    }
                    console.log();
                }
                if (credentialStatus.missing.length > 0) {
                    console.log(chalk.bold('Missing credentials:'));
                    for (const svc of credentialStatus.missing) {
                        console.log(chalk.yellow(`  • ${svc}`));
                    }
                    console.log();
                    // Skip credential setup prompt in non-interactive mode
                    if (!nonInteractive) {
                        const { setupMissing } = await inquirer.prompt([
                            {
                                type: 'confirm',
                                name: 'setupMissing',
                                message: 'Set up missing credentials now?',
                                default: true,
                            },
                        ]);
                        if (setupMissing) {
                            console.log();
                            for (const service of credentialStatus.missing) {
                                const { execSync } = await import('child_process');
                                try {
                                    execSync(`cv auth setup ${service}`, { stdio: 'inherit' });
                                }
                                catch {
                                    console.log(chalk.yellow(`Skipped ${service}. Run 'cv auth setup ${service}' later.`));
                                }
                            }
                        }
                    }
                }
                console.log();
                console.log(chalk.bold('Next steps:'));
                if (credentialStatus.missing.length > 0) {
                    console.log(chalk.gray('  1. Set up missing credentials:'));
                    console.log(chalk.cyan('     cv auth setup'));
                    console.log();
                    console.log(chalk.gray('  2. Sync your repository:'));
                }
                else {
                    console.log(chalk.gray('  1. Sync your repository:'));
                }
                console.log(chalk.cyan('     cv sync'));
                console.log();
                console.log(chalk.gray('  Then start using CV-Git:'));
                console.log(chalk.cyan('     cv find "authentication logic"'));
                console.log(chalk.cyan('     cv code "add logging to error handlers"'));
                console.log();
            }
        }
        catch (error) {
            output.error('Failed to initialize CV-Git', error);
            process.exit(1);
        }
    });
    return cmd;
}
/**
 * Initialize single repo mode
 */
async function initSingleRepo(repoRoot, repoName, spinner, output) {
    spinner.text = 'Creating configuration...';
    await configManager.init(repoRoot, repoName);
}
/**
 * Initialize workspace mode
 */
async function initWorkspace(workspaceRoot, workspaceName, childRepos, spinner, output) {
    spinner.text = 'Creating workspace configuration...';
    const workspace = {
        version: '1.0.0',
        name: workspaceName,
        root: workspaceRoot,
        repos: childRepos,
        createdAt: new Date().toISOString(),
        graphDatabase: generateDatabaseName(workspaceName),
    };
    await saveWorkspace(workspace);
    // Also create a minimal config.json for compatibility
    spinner.text = 'Creating configuration...';
    await configManager.init(workspaceRoot, workspaceName);
}
/**
 * Check which global credentials are already configured
 */
async function checkGlobalCredentials(services) {
    const credentials = new CredentialManager();
    await credentials.init();
    const configured = [];
    const missing = [];
    for (const service of services) {
        let hasCredential = false;
        try {
            switch (service) {
                case 'github':
                    hasCredential = !!(await credentials.getGitPlatformToken('github'));
                    break;
                case 'gitlab':
                    hasCredential = !!(await credentials.getGitPlatformToken('gitlab'));
                    break;
                case 'bitbucket':
                    hasCredential = !!(await credentials.getGitPlatformToken('bitbucket'));
                    break;
                case 'anthropic':
                    hasCredential = !!(await credentials.getAnthropicKey());
                    break;
                case 'openai':
                    hasCredential = !!(await credentials.getOpenAIKey());
                    break;
                case 'openrouter':
                    hasCredential = !!(await credentials.getOpenRouterKey());
                    break;
            }
        }
        catch {
            hasCredential = false;
        }
        if (hasCredential) {
            configured.push(service);
        }
        else {
            missing.push(service);
        }
    }
    return { configured, missing };
}
//# sourceMappingURL=init.js.map