/*
 * 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 { ALL_PROFILES } from '../../../profiles/index.js';
import { autoExpandProfiles } from '../../../services/profile-expand.js';
import { createTask, taskStatePath } from '../../../services/task-state.js';
import { readWorkspaceConfig } from '../../../services/workspace-config.js';
import { WORKFLOW_PHASES, } from '../../../types/index.js';
import { splitCsv, taskIdentifierFlags } from '../../../util/task-flags.js';
import { resolveWorkspaceRoot } from '../../../services/workspace-root.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@jterrats/setup-agents', 'setup-agents.task.create');
const PROFILE_HELP_VALUE = ALL_PROFILES.map((profile) => profile.id).join('|');
const WORKSPACE_MODES = ['project', 'advisory'];
export default class TaskCreate extends SfCommand {
    static summary = messages.getMessage('summary');
    static description = messages.getMessage('description');
    static examples = messages.getMessages('examples');
    static flags = {
        ...taskIdentifierFlags,
        summary: Flags.string({
            char: 's',
            summary: messages.getMessage('flags.summary.summary'),
            description: messages.getMessage('flags.summary.description'),
            required: true,
        }),
        role: Flags.string({
            char: 'r',
            summary: messages.getMessage('flags.role.summary'),
            description: messages.getMessage('flags.role.description'),
        }),
        profile: Flags.string({
            char: 'p',
            summary: messages.getMessage('flags.profile.summary'),
            description: messages.getMessage('flags.profile.description'),
            helpValue: PROFILE_HELP_VALUE,
        }),
        mode: Flags.string({
            summary: messages.getMessage('flags.mode.summary'),
            description: messages.getMessage('flags.mode.description'),
            options: [...WORKSPACE_MODES],
        }),
        evidence: Flags.string({
            summary: messages.getMessage('flags.evidence.summary'),
            description: messages.getMessage('flags.evidence.description'),
        }),
        'required-roles': Flags.string({
            summary: messages.getMessage('flags.required-roles.summary'),
            description: messages.getMessage('flags.required-roles.description'),
            helpValue: PROFILE_HELP_VALUE,
        }),
        'optional-roles': Flags.string({
            summary: messages.getMessage('flags.optional-roles.summary'),
            description: messages.getMessage('flags.optional-roles.description'),
            helpValue: PROFILE_HELP_VALUE,
        }),
        'declared-phases': Flags.string({
            summary: messages.getMessage('flags.declared-phases.summary'),
            description: messages.getMessage('flags.declared-phases.description'),
            helpValue: WORKFLOW_PHASES.join('|'),
        }),
    };
    async run() {
        const { flags } = await this.parse(TaskCreate);
        const cwd = resolveWorkspaceRoot(flags);
        const profile = flags.profile ?? flags.role;
        const roles = resolveRoles(flags['required-roles'], flags['optional-roles'], profile);
        const declaredPhases = resolveDeclaredPhases(flags['declared-phases']);
        const record = createTask(cwd, {
            id: flags.id ?? flags.task,
            summary: flags.summary,
            profile,
            mode: flags.mode,
            roles,
            declaredPhases,
            evidenceIds: splitCsv(flags.evidence),
        });
        const file = taskStatePath(cwd);
        if (roles) {
            this.tryAutoExpandRoles(cwd, roles);
        }
        this.log(messages.getMessage('info.created', [record.id, file]));
        return { record, file, cwd };
    }
    tryAutoExpandRoles(cwd, roles) {
        const config = readWorkspaceConfig(cwd);
        if (!config)
            return;
        const allRoles = [...roles.required, ...roles.optional];
        const configSet = new Set(config.profiles);
        const missingFromConfig = allRoles.filter((r) => !configSet.has(r));
        if (missingFromConfig.length === 0)
            return;
        const expandResult = autoExpandProfiles(cwd, missingFromConfig, config.tools);
        if (expandResult.expanded.length > 0) {
            this.log(`Auto-expanded profiles: ${expandResult.expanded.join(', ')} (${expandResult.filesWritten.length} files)`);
        }
        if (expandResult.invalid.length > 0) {
            this.warn(`Unknown roles ignored: ${expandResult.invalid.join(', ')}`);
        }
    }
}
function resolveRoles(requiredFlag, optionalFlag, profile) {
    const requiredRoles = splitCsv(requiredFlag);
    const optionalRoles = splitCsv(optionalFlag);
    if (requiredRoles.length > 0 || optionalRoles.length > 0) {
        return { required: requiredRoles, optional: optionalRoles };
    }
    if (profile) {
        return { required: [profile], optional: [] };
    }
    return undefined;
}
function resolveDeclaredPhases(flag) {
    const rawPhases = splitCsv(flag);
    if (rawPhases.length === 0)
        return undefined;
    return rawPhases.filter((p) => WORKFLOW_PHASES.includes(p));
}
//# sourceMappingURL=create.js.map