/**
 * studiograph init command
 *
 * Initializes a new Studiograph workspace in the current directory
 */
import { Command } from 'commander';
import { intro, confirm, outro, spinner, log } from '@clack/prompts';
import { existsSync, mkdirSync } from 'fs';
import { execFileSync } from 'child_process';
import { join, resolve } from 'path';
import { dimText } from '../colors.js';
import { Workspace } from '../../core/workspace.js';
import { runPreflight } from '../../utils/preflight.js';
export const initCommand = new Command('init')
    .description('Initialize a new Studiograph workspace')
    .argument('<team-name>', 'Name of your team (e.g., "Acme Studios")')
    .argument('[directory]', 'Directory to create workspace in (default: derived from team name, use "." for current directory)')
    .action(async (teamName, directory) => {
    console.log();
    intro('Studiograph Workspace Setup');
    const ready = runPreflight();
    if (!ready) {
        process.exit(1);
        return;
    }
    // Determine target directory
    let targetDir;
    if (directory === '.') {
        // Use current directory (must be empty or non-existent)
        targetDir = process.cwd();
        const workspace = new Workspace(targetDir);
        if (workspace.isWorkspace()) {
            outro('❌ Already a Studiograph workspace');
            process.exit(1);
        }
    }
    else if (directory) {
        // Use specified directory
        targetDir = resolve(directory);
    }
    else {
        // Auto-generate from team name slug
        const slug = teamName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
        targetDir = resolve(slug);
    }
    // Check if target directory exists and has .studiograph
    const studiographDir = join(targetDir, '.studiograph');
    if (existsSync(studiographDir)) {
        outro(`❌ A .studiograph directory already exists at ${targetDir}`);
        process.exit(1);
    }
    // Create target directory if needed
    if (!existsSync(targetDir)) {
        mkdirSync(targetDir, { recursive: true });
        log.info(`Created directory: ${targetDir}`);
    }
    else if (directory !== '.') {
        // Directory exists but is not current dir - check if empty
        const { readdirSync } = await import('fs');
        const files = readdirSync(targetDir);
        if (files.length > 0) {
            const proceed = await confirm({
                message: `Directory ${targetDir} is not empty. Continue anyway?`,
                initialValue: false,
            });
            if (!proceed || typeof proceed === 'symbol') {
                outro('Cancelled');
                process.exit(0);
            }
        }
    }
    // Initialize workspace
    const workspace = new Workspace(targetDir);
    workspace.quietMigrations = true;
    const s = spinner();
    s.start('Creating workspace...');
    try {
        workspace.init(teamName);
        s.stop('Workspace created');
        // Commit the .studiograph config repo (workspace.json + .gitignore)
        // so a freshly-initialized workspace has a clean baseline commit.
        const configPath = join(targetDir, '.studiograph');
        try {
            execFileSync('git', ['add', '-A'], { cwd: configPath, stdio: 'pipe' });
            execFileSync('git', ['commit', '-m', 'Initial workspace setup'], { cwd: configPath, stdio: 'pipe' });
        }
        catch { /* non-fatal */ }
        const cdStep = directory === '.' ? '' : `cd ${targetDir} && `;
        log.info('Next steps:');
        log.info(`  ${cdStep}studiograph serve     ${dimText('Boot the workspace + open the web UI')}`);
        outro(`✨ Workspace initialized!`);
    }
    catch (error) {
        s.stop('Failed');
        outro(`❌ Error: ${error instanceof Error ? error.message : 'Unknown error'}`);
        process.exit(1);
    }
});
//# sourceMappingURL=init.js.map