/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { mkdirSync, existsSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { Messages } from '@salesforce/core';
import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
import { generateDefaultPlaybooks, PLAYBOOKS_DIR } from '../../../generators/playbook-generator.js';
import { DEFAULT_INSTRUCTIONS_DIR, resolveAllPhaseInstructions } from '../../../services/workflow-engine.js';
import { PLUGIN_VERSION } from '../../../version.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@jterrats/setup-agents', 'setup-agents.workflow.playbooks');
export default class WorkflowPlaybooks extends SfCommand {
    static summary = messages.getMessage('summary');
    static description = messages.getMessage('description');
    static examples = messages.getMessages('examples');
    static flags = {
        'instructions-dir': Flags.string({
            summary: messages.getMessage('flags.instructions-dir.summary'),
            description: messages.getMessage('flags.instructions-dir.description'),
            default: DEFAULT_INSTRUCTIONS_DIR,
        }),
        scaffold: Flags.boolean({
            summary: messages.getMessage('flags.scaffold.summary'),
            description: messages.getMessage('flags.scaffold.description'),
            default: false,
        }),
        phase: Flags.string({
            summary: messages.getMessage('flags.phase.summary'),
            description: messages.getMessage('flags.phase.description'),
        }),
        'dry-run': Flags.boolean({
            summary: messages.getMessage('flags.dry-run.summary'),
            default: false,
        }),
    };
    async run() {
        const { flags } = await this.parse(WorkflowPlaybooks);
        const cwd = process.cwd();
        const instructionsDir = flags['instructions-dir'] ?? PLAYBOOKS_DIR;
        const phases = resolveAllPhaseInstructions(cwd, instructionsDir);
        const resolvedDir = phases[0]?.instructionsDir ?? join(cwd, instructionsDir);
        this.log(messages.getMessage('info.header', [resolvedDir]));
        this.logPhasePlaybooks(phases);
        const { scaffolded, skipped } = flags.scaffold
            ? this.scaffoldPlaybooks(phases, resolvedDir, flags.phase, flags['dry-run'])
            : { scaffolded: [], skipped: [] };
        return { phases, instructionsDir: resolvedDir, cwd, scaffolded, skipped };
    }
    logPhasePlaybooks(phases) {
        for (const phase of phases) {
            this.log('');
            this.log(messages.getMessage('info.phase', [phase.phase]));
            for (const p of phase.playbooks) {
                const mark = p.exists ? '✓' : '✗';
                this.log(messages.getMessage('info.playbook', [mark, p.filename, p.path]));
            }
        }
    }
    scaffoldPlaybooks(phases, resolvedDir, phaseFilter, dryRun) {
        const scaffolded = [];
        const skipped = [];
        const allPlaybooks = generateDefaultPlaybooks(PLUGIN_VERSION);
        const candidates = (phaseFilter ? phases.filter((p) => p.phase === phaseFilter) : phases)
            .flatMap((p) => p.playbooks)
            .filter((pb) => pb.filename in allPlaybooks);
        if (!dryRun && candidates.some((pb) => !existsSync(pb.path))) {
            mkdirSync(resolvedDir, { recursive: true });
        }
        for (const pb of candidates) {
            if (existsSync(pb.path)) {
                skipped.push(pb.path);
            }
            else if (dryRun) {
                this.log(`  [dry-run] would create: ${pb.path}`);
                scaffolded.push(pb.path);
            }
            else {
                writeFileSync(pb.path, allPlaybooks[pb.filename], 'utf8');
                this.log(`  created: ${pb.path}`);
                scaffolded.push(pb.path);
            }
        }
        if (scaffolded.length === 0 && skipped.length === 0 && !dryRun) {
            this.log('All playbooks already exist — nothing to scaffold.');
        }
        return { scaffolded, skipped };
    }
}
//# sourceMappingURL=playbooks.js.map