"use strict";
/**
 * Create Workflow Command
 * Interactive wizard for creating workflows from scratch
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createWorkflowCommand = createWorkflowCommand;
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const inquirer_1 = __importDefault(require("inquirer"));
const output = __importStar(require("../output"));
async function createWorkflowCommand() {
    const spinner = output.spinner('');
    try {
        // Show banner
        output.banner('Create Workflow', 'Interactive wizard to create a new workflow');
        output.info('This wizard will help you create a complete workflow definition.');
        output.blank();
        // Basic information
        const basic = await inquirer_1.default.prompt([
            {
                type: 'input',
                name: 'workflowName',
                message: 'Workflow name:',
                validate: (input) => {
                    if (!input || input.trim().length === 0) {
                        return 'Workflow name is required';
                    }
                    if (!/^[a-zA-Z0-9-\s]+$/.test(input)) {
                        return 'Workflow name can only contain letters, numbers, spaces, and hyphens';
                    }
                    return true;
                },
            },
            {
                type: 'input',
                name: 'description',
                message: 'Description:',
                default: 'A Bangstack workflow',
            },
            {
                type: 'list',
                name: 'workflowType',
                message: 'What type of project are you building?',
                choices: [
                    { name: 'Full-Stack Web Application (Frontend + Backend + Database)', value: 'full-stack' },
                    { name: 'Frontend Only (SPA or Static Site)', value: 'frontend-only' },
                    { name: 'Backend API Only', value: 'backend-only' },
                    { name: 'Data Pipeline or Script', value: 'data-pipeline' },
                    { name: 'Custom (choose each component)', value: 'custom' },
                ],
            },
        ]);
        output.blank();
        output.header('Stack Configuration');
        let answers = { ...basic };
        // Frontend selection
        if (basic.workflowType === 'full-stack' || basic.workflowType === 'frontend-only' || basic.workflowType === 'custom') {
            const frontendQuestions = await inquirer_1.default.prompt([
                {
                    type: 'list',
                    name: 'frontend',
                    message: 'Frontend framework:',
                    choices: [
                        { name: 'React', value: 'react' },
                        { name: 'Vue', value: 'vue' },
                        { name: 'Angular', value: 'angular' },
                        { name: 'Svelte', value: 'svelte' },
                        { name: 'Next.js', value: 'nextjs' },
                        { name: 'None', value: null },
                    ],
                    when: basic.workflowType !== 'frontend-only',
                },
                {
                    type: 'list',
                    name: 'frontendLanguage',
                    message: 'Frontend language:',
                    choices: [
                        { name: 'TypeScript', value: 'typescript' },
                        { name: 'JavaScript', value: 'javascript' },
                    ],
                    default: 'typescript',
                    when: (a) => a.frontend || basic.workflowType === 'frontend-only',
                },
                {
                    type: 'list',
                    name: 'frontendStyling',
                    message: 'Styling approach:',
                    choices: [
                        { name: 'Tailwind CSS', value: 'tailwind' },
                        { name: 'CSS Modules', value: 'css-modules' },
                        { name: 'Styled Components', value: 'styled-components' },
                        { name: 'Plain CSS', value: 'css' },
                    ],
                    default: 'tailwind',
                    when: (a) => a.frontend || basic.workflowType === 'frontend-only',
                },
            ]);
            answers = { ...answers, ...frontendQuestions };
        }
        // Backend selection
        if (basic.workflowType === 'full-stack' || basic.workflowType === 'backend-only' || basic.workflowType === 'custom') {
            const backendQuestions = await inquirer_1.default.prompt([
                {
                    type: 'list',
                    name: 'backend',
                    message: 'Backend framework:',
                    choices: [
                        { name: 'Express (Node.js)', value: 'express' },
                        { name: 'Fastify (Node.js)', value: 'fastify' },
                        { name: 'NestJS (Node.js)', value: 'nestjs' },
                        { name: 'FastAPI (Python)', value: 'fastapi' },
                        { name: 'Django (Python)', value: 'django' },
                        { name: 'Gin (Go)', value: 'gin' },
                        { name: 'None', value: null },
                    ],
                    when: basic.workflowType !== 'backend-only',
                },
                {
                    type: 'list',
                    name: 'backendLanguage',
                    message: 'Backend language:',
                    choices: (a) => {
                        if (a.backend === 'fastapi' || a.backend === 'django') {
                            return [{ name: 'Python', value: 'python' }];
                        }
                        else if (a.backend === 'gin') {
                            return [{ name: 'Go', value: 'go' }];
                        }
                        return [
                            { name: 'TypeScript', value: 'typescript' },
                            { name: 'JavaScript', value: 'javascript' },
                        ];
                    },
                    default: (a) => {
                        if (a.backend === 'fastapi' || a.backend === 'django')
                            return 'python';
                        if (a.backend === 'gin')
                            return 'go';
                        return 'typescript';
                    },
                    when: (a) => a.backend || basic.workflowType === 'backend-only',
                },
            ]);
            answers = { ...answers, ...backendQuestions };
        }
        // Database selection
        if (basic.workflowType === 'full-stack' || basic.workflowType === 'backend-only' || basic.workflowType === 'custom') {
            const databaseQuestions = await inquirer_1.default.prompt([
                {
                    type: 'list',
                    name: 'database',
                    message: 'Database:',
                    choices: [
                        { name: 'PostgreSQL', value: 'postgresql' },
                        { name: 'MySQL', value: 'mysql' },
                        { name: 'MongoDB', value: 'mongodb' },
                        { name: 'SQLite (for development)', value: 'sqlite' },
                        { name: 'None', value: null },
                    ],
                },
                {
                    type: 'list',
                    name: 'databaseORM',
                    message: 'ORM/ODM:',
                    choices: (a) => {
                        if (a.database === 'mongodb') {
                            return [
                                { name: 'Mongoose', value: 'mongoose' },
                                { name: 'Prisma', value: 'prisma' },
                            ];
                        }
                        return [
                            { name: 'Prisma', value: 'prisma' },
                            { name: 'Drizzle', value: 'drizzle' },
                            { name: 'TypeORM', value: 'typeorm' },
                        ];
                    },
                    default: 'prisma',
                    when: (a) => a.database,
                },
            ]);
            answers = { ...answers, ...databaseQuestions };
        }
        // Cache selection
        if (basic.workflowType === 'full-stack' || basic.workflowType === 'backend-only') {
            const cacheQuestions = await inquirer_1.default.prompt([
                {
                    type: 'confirm',
                    name: 'addCache',
                    message: 'Add caching layer (Redis)?',
                    default: false,
                },
                {
                    type: 'list',
                    name: 'cache',
                    message: 'Cache provider:',
                    choices: [
                        { name: 'Upstash Redis (serverless)', value: 'upstash-redis' },
                        { name: 'Redis (self-hosted)', value: 'redis' },
                    ],
                    default: 'upstash-redis',
                    when: (a) => a.addCache,
                },
            ]);
            answers = { ...answers, ...cacheQuestions };
        }
        // Features
        output.blank();
        output.header('Additional Features');
        const features = await inquirer_1.default.prompt([
            {
                type: 'confirm',
                name: 'hasAuth',
                message: 'Include authentication?',
                default: true,
                when: basic.workflowType === 'full-stack' || basic.workflowType === 'backend-only',
            },
            {
                type: 'confirm',
                name: 'hasTests',
                message: 'Include test configuration?',
                default: true,
            },
            {
                type: 'confirm',
                name: 'hasDocker',
                message: 'Include Docker configuration?',
                default: true,
            },
            {
                type: 'confirm',
                name: 'hasCICD',
                message: 'Include CI/CD (GitHub Actions)?',
                default: false,
            },
        ]);
        answers = { ...answers, ...features };
        // Models (Extended Schema)
        if (answers.database) {
            output.blank();
            output.header('Data Models');
            const modelsIntro = await inquirer_1.default.prompt([
                {
                    type: 'confirm',
                    name: 'addModels',
                    message: 'Define data models now?',
                    default: true,
                },
            ]);
            if (modelsIntro.addModels) {
                answers.models = await promptForModels();
            }
        }
        // Generate workflow file
        output.blank();
        output.header('Generating Workflow');
        spinner.text = 'Creating workflow file...';
        spinner.start();
        const workflowContent = generateWorkflowContent(answers);
        const workflowId = answers.workflowName.toLowerCase().replace(/[^a-z0-9-]/g, '-');
        const filename = `${workflowId}.workflow.yaml`;
        // Determine output path
        const outputPath = path.resolve(process.cwd(), filename);
        if (fs.existsSync(outputPath)) {
            spinner.stop();
            const overwrite = await inquirer_1.default.prompt([
                {
                    type: 'confirm',
                    name: 'confirmed',
                    message: `File ${filename} already exists. Overwrite?`,
                    default: false,
                },
            ]);
            if (!overwrite.confirmed) {
                output.warning('Workflow creation cancelled');
                process.exit(0);
            }
            spinner.start();
        }
        fs.writeFileSync(outputPath, workflowContent);
        spinner.succeed(`Created workflow: ${filename}`);
        // Success summary
        output.blank();
        output.success('Workflow created successfully!');
        output.blank();
        // Show summary
        output.header('Workflow Summary');
        const summaryItems = [
            ['Name', output.bold(answers.workflowName)],
            ['File', output.path(filename)],
        ];
        if (answers.frontend) {
            summaryItems.push(['Frontend', `${answers.frontend} (${answers.frontendLanguage})`]);
        }
        if (answers.backend) {
            summaryItems.push(['Backend', `${answers.backend} (${answers.backendLanguage})`]);
        }
        if (answers.database) {
            summaryItems.push(['Database', `${answers.database} with ${answers.databaseORM}`]);
        }
        if (answers.cache) {
            summaryItems.push(['Cache', answers.cache]);
        }
        if (answers.models) {
            summaryItems.push(['Models', `${answers.models.length} defined`]);
        }
        output.table(summaryItems);
        // Next steps
        output.blank();
        output.header('Next Steps');
        output.list([
            `Review and edit: ${output.code(filename)}`,
            `Validate workflow: ${output.code(`bang validate ${filename}`)}`,
            `Generate code: ${output.code(`bang generate ${filename} --output ./generated`)}`,
        ], 'blue');
        output.blank();
    }
    catch (error) {
        spinner.fail('Workflow creation failed');
        output.blank();
        if (error instanceof Error) {
            output.error(error.message);
        }
        else {
            output.error(String(error));
        }
        process.exit(1);
    }
}
/**
 * Prompt for model definitions
 */
async function promptForModels() {
    const models = [];
    output.info('Define your data models (e.g., User, Post, Comment)');
    output.blank();
    let addMore = true;
    while (addMore) {
        const modelBasic = await inquirer_1.default.prompt([
            {
                type: 'input',
                name: 'name',
                message: 'Model name (PascalCase, e.g., User, BlogPost):',
                validate: (input) => {
                    if (!input || input.trim().length === 0) {
                        return 'Model name is required';
                    }
                    if (!/^[A-Z][a-zA-Z0-9]*$/.test(input)) {
                        return 'Model name must be PascalCase (e.g., User, BlogPost)';
                    }
                    if (models.some(m => m.name === input)) {
                        return 'Model with this name already exists';
                    }
                    return true;
                },
            },
            {
                type: 'input',
                name: 'description',
                message: 'Model description:',
                default: (a) => `${a.name} model`,
            },
        ]);
        // Add default system fields
        const fields = [
            { name: 'id', type: 'uuid', required: true },
            { name: 'created_at', type: 'timestamp', required: true },
            { name: 'updated_at', type: 'timestamp', required: true },
        ];
        output.info(`Adding fields to ${modelBasic.name}...`);
        let addMoreFields = true;
        while (addMoreFields) {
            const field = await inquirer_1.default.prompt([
                {
                    type: 'input',
                    name: 'name',
                    message: 'Field name (snake_case):',
                    validate: (input) => {
                        if (!input || input.trim().length === 0) {
                            return 'Field name is required';
                        }
                        if (!/^[a-z][a-z0-9_]*$/.test(input)) {
                            return 'Field name must be snake_case (e.g., user_name, email_address)';
                        }
                        if (fields.some(f => f.name === input)) {
                            return 'Field with this name already exists';
                        }
                        return true;
                    },
                },
                {
                    type: 'list',
                    name: 'type',
                    message: 'Field type:',
                    choices: [
                        { name: 'String', value: 'string' },
                        { name: 'Text (long string)', value: 'text' },
                        { name: 'Integer', value: 'integer' },
                        { name: 'Float', value: 'float' },
                        { name: 'Boolean', value: 'boolean' },
                        { name: 'UUID', value: 'uuid' },
                        { name: 'Date', value: 'date' },
                        { name: 'Timestamp', value: 'timestamp' },
                        { name: 'JSON', value: 'json' },
                        { name: 'Enum', value: 'enum' },
                    ],
                },
                {
                    type: 'confirm',
                    name: 'required',
                    message: 'Required field?',
                    default: false,
                },
                {
                    type: 'confirm',
                    name: 'unique',
                    message: 'Unique field?',
                    default: false,
                },
                {
                    type: 'input',
                    name: 'default',
                    message: 'Default value (leave empty for none):',
                    when: (a) => !a.required,
                },
            ]);
            fields.push(field);
            const continueFields = await inquirer_1.default.prompt([
                {
                    type: 'confirm',
                    name: 'continue',
                    message: 'Add another field?',
                    default: true,
                },
            ]);
            addMoreFields = continueFields.continue;
        }
        models.push({
            ...modelBasic,
            fields,
        });
        const continueModels = await inquirer_1.default.prompt([
            {
                type: 'confirm',
                name: 'continue',
                message: 'Add another model?',
                default: false,
            },
        ]);
        addMore = continueModels.continue;
        if (addMore) {
            output.blank();
        }
    }
    return models;
}
/**
 * Generate workflow YAML content
 */
function generateWorkflowContent(answers) {
    const workflowId = answers.workflowName.toLowerCase().replace(/[^a-z0-9-]/g, '-');
    let yaml = `# ${answers.workflowName} Workflow
# Generated by Bangstack interactive wizard

workflow:
  id: ${workflowId}
  version: 1.0.0
  name: ${answers.workflowName}
  description: ${answers.description}

`;
    // Technology section (extended schema)
    if (answers.models || answers.frontend || answers.backend || answers.database) {
        yaml += `technology:\n`;
        if (answers.frontend) {
            yaml += `  frontend:
    framework: ${answers.frontend}
    language: ${answers.frontendLanguage}
    styling: ${answers.frontendStyling}
`;
        }
        if (answers.backend) {
            yaml += `  backend:
    framework: ${answers.backend}
    language: ${answers.backendLanguage}
`;
        }
        if (answers.database) {
            yaml += `  database:
    type: ${answers.database}
    orm: ${answers.databaseORM}
    version: "${answers.database === 'postgresql' ? '15' : 'latest'}"
`;
        }
        if (answers.cache) {
            yaml += `  cache:
    provider: ${answers.cache}
`;
        }
        yaml += '\n';
    }
    // Models section (extended schema)
    if (answers.models && answers.models.length > 0) {
        yaml += `models:\n`;
        for (const model of answers.models) {
            yaml += `  ${model.name}:
    description: ${model.description}
    fields:\n`;
            for (const field of model.fields) {
                yaml += `      ${field.name}:
        type: ${field.type}
        ${field.required ? 'required: true' : ''}
        ${field.unique ? 'unique: true' : ''}
        ${field.default ? `default: ${field.default}` : ''}
        ${['id', 'created_at', 'updated_at'].includes(field.name) ? 'system_field: true' : ''}
`;
            }
        }
        yaml += '\n';
    }
    // Stack section (legacy format for compatibility)
    yaml += `stack:\n`;
    if (answers.frontend) {
        yaml += `  frontend:
    type: frontend
    technology: ${answers.frontend}
    directory: frontend
`;
    }
    if (answers.backend) {
        yaml += `  backend:
    type: backend
    technology: ${answers.backendLanguage}/${answers.backend}
    directory: backend
`;
    }
    if (answers.database) {
        yaml += `  database:
    type: database
    technology: ${answers.database}/${answers.databaseORM}
    directory: database
`;
    }
    if (answers.hasDocker) {
        yaml += `  docker:
    type: infrastructure
    technology: docker
`;
    }
    if (answers.hasCICD) {
        yaml += `  ci:
    type: infrastructure
    technology: github-actions
`;
    }
    return yaml;
}
//# sourceMappingURL=create-workflow.js.map