import select from '@inquirer/select';
import { Command, Flags } from '@oclif/core';
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const templatesDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'src', 'templates', 'pipeline');
export default class Pipeline extends Command {
    static description = 'Generate a deploy workflow from templates (interactive).';
    static examples = [
        '<%= config.bin %> pipeline',
        '<%= config.bin %> pipeline --force',
    ];
    static flags = {
        force: Flags.boolean({
            char: 'f',
            default: false,
            description: 'Overwrite existing workflow file',
        }),
    };
    async run() {
        const { flags } = await this.parse(Pipeline);
        const from = await this.selectFrom();
        const to = await this.selectTo(from);
        const templatePath = resolve(templatesDir, from, to, 'deploy.yml');
        if (!existsSync(templatePath)) {
            this.error(`Template not found: ${templatePath}`);
        }
        const outputPath = resolve('.github/workflows/deploy.yml');
        if (existsSync(outputPath) && !flags.force) {
            this.error(`${outputPath} already exists. Use --force to overwrite.`);
        }
        const content = readFileSync(templatePath, 'utf8');
        mkdirSync(dirname(outputPath), { recursive: true });
        writeFileSync(outputPath, content, 'utf8');
        this.log(`Workflow generated: ${outputPath}`);
    }
    async selectFrom() {
        const choices = readdirSync(templatesDir, { withFileTypes: true })
            .filter((d) => d.isDirectory())
            .map((d) => ({ name: d.name, value: d.name }));
        if (choices.length === 1)
            return choices[0].value;
        return select({
            choices,
            message: 'From which CI/CD platform will you deploy?',
        });
    }
    async selectTo(from) {
        const fromDir = resolve(templatesDir, from);
        const choices = readdirSync(fromDir, { withFileTypes: true })
            .filter((d) => d.isDirectory())
            .map((d) => ({ name: d.name, value: d.name }));
        if (choices.length === 1)
            return choices[0].value;
        return select({
            choices,
            message: 'To which hosting platform will it be deployed?',
        });
    }
}
