/*
 * 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 { Messages } from '@salesforce/core';
import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
import { buildPhasePlan } from '../../../phases/registry.js';
import { getTask, updateTaskRecord } from '../../../services/task-state.js';
import { readWorkspaceConfig } from '../../../services/workspace-config.js';
import { PHASE_SEQUENCE } from '../../../services/workflow-instructions.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@jterrats/setup-agents', 'setup-agents.workflow.phase-plan');
export default class WorkflowPhasePlan extends SfCommand {
    static summary = messages.getMessage('summary');
    static description = messages.getMessage('description');
    static examples = messages.getMessages('examples');
    static flags = {
        story: Flags.string({
            char: 's',
            summary: messages.getMessage('flags.story.summary'),
            description: messages.getMessage('flags.story.description'),
            required: true,
        }),
        'skip-phase': Flags.string({
            summary: messages.getMessage('flags.skip-phase.summary'),
            description: messages.getMessage('flags.skip-phase.description'),
            multiple: true,
            options: [...PHASE_SEQUENCE],
        }),
        'add-phase': Flags.string({
            summary: messages.getMessage('flags.add-phase.summary'),
            description: messages.getMessage('flags.add-phase.description'),
            multiple: true,
            options: [...PHASE_SEQUENCE],
        }),
        'require-gate': Flags.string({
            summary: messages.getMessage('flags.require-gate.summary'),
            description: messages.getMessage('flags.require-gate.description'),
            multiple: true,
            options: [...PHASE_SEQUENCE],
        }),
        'remove-gate': Flags.string({
            summary: messages.getMessage('flags.remove-gate.summary'),
            description: messages.getMessage('flags.remove-gate.description'),
            multiple: true,
            options: [...PHASE_SEQUENCE],
        }),
        save: Flags.boolean({
            summary: messages.getMessage('flags.save.summary'),
            description: messages.getMessage('flags.save.description'),
            default: false,
        }),
    };
    async run() {
        const { flags } = await this.parse(WorkflowPhasePlan);
        const cwd = process.cwd();
        const storyId = flags.story;
        const config = readWorkspaceConfig(cwd);
        const task = getTask(cwd, storyId);
        const taskRoles = task?.roles;
        const cliOverrides = buildOverridesFromFlags(flags['skip-phase'], flags['add-phase'], flags['require-gate'], flags['remove-gate']);
        const allOverrides = [...(task?.phaseOverrides ?? []), ...cliOverrides];
        const result = buildPhasePlan({
            taskRoles: taskRoles ?? undefined,
            activeProfiles: config?.profiles,
            overrides: allOverrides,
        });
        this.log(messages.getMessage('info.planHeader', [storyId]));
        for (const entry of result.included) {
            const gateMarker = entry.gateAfter ? '[GATE]' : '';
            this.log(messages.getMessage('info.planPhase', [entry.phase.padEnd(16), entry.profile, entry.source, gateMarker]));
        }
        for (const skip of result.skipped) {
            this.log(messages.getMessage('info.skipped', [skip.phase, skip.reason]));
        }
        if (result.gates.length > 0) {
            this.log(messages.getMessage('info.gates', [result.gates.join(', ')]));
        }
        if (flags.save && task && cliOverrides.length > 0) {
            updateTaskRecord(cwd, task.id, { phaseOverrides: allOverrides });
            this.log(messages.getMessage('info.saved', [task.id]));
        }
        return {
            plan: result.included.map((e) => ({
                phase: e.phase,
                profile: e.profile,
                source: e.source,
                gateAfter: e.gateAfter,
            })),
            skipped: result.skipped,
            gates: result.gates,
            cwd,
        };
    }
}
function buildOverridesFromFlags(skipPhases, addPhases, requireGates, removeGates) {
    const overrides = [];
    const toOverride = (phases, action) => {
        if (!phases)
            return;
        for (const phase of phases) {
            overrides.push({ phase: phase, action });
        }
    };
    toOverride(skipPhases, 'skip');
    toOverride(addPhases, 'add');
    toOverride(requireGates, 'require-gate');
    toOverride(removeGates, 'remove-gate');
    return overrides;
}
//# sourceMappingURL=phase-plan.js.map