/*
 * 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 { syncClassCatalog } from '../../../services/class-catalog-sync.js';
import { listRecords } from '../../../services/orchestration-records.js';
import { completeTask, getTask, taskStatePath } from '../../../services/task-state.js';
import { pushToGitHub, pushToJira } from '../../../services/write-back.js';
import { resolveTaskId, 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.done');
const PROFILE_HELP_VALUE = ALL_PROFILES.map((profile) => profile.id).join('|');
export default class TaskDone extends SfCommand {
    static summary = messages.getMessage('summary');
    static description = messages.getMessage('description');
    static examples = messages.getMessages('examples');
    static flags = {
        ...taskIdentifierFlags,
        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,
        }),
        evidence: Flags.string({
            summary: messages.getMessage('flags.evidence.summary'),
            description: messages.getMessage('flags.evidence.description'),
        }),
        'push-to': Flags.string({
            summary: messages.getMessage('flags.push-to.summary'),
            options: ['github', 'jira'],
        }),
        'dry-run': Flags.boolean({
            summary: messages.getMessage('flags.dry-run.summary'),
            default: false,
        }),
        ticket: Flags.string({
            summary: messages.getMessage('flags.ticket.summary'),
        }),
    };
    async run() {
        const { flags } = await this.parse(TaskDone);
        const cwd = resolveWorkspaceRoot(flags);
        const file = taskStatePath(cwd);
        const taskId = resolveTaskId(flags);
        if (!getTask(cwd, taskId))
            throw new Error(messages.getMessage('errors.notFound', [taskId]));
        const record = completeTask(cwd, {
            id: taskId,
            profile: flags.profile ?? flags.role,
            evidenceIds: splitCsv(flags.evidence),
        });
        this.log(messages.getMessage('info.done', [record.id, file]));
        const catalogUpdates = syncClassCatalog(cwd, taskId);
        if (catalogUpdates > 0) {
            this.log(`Updated class-catalog.md with ${catalogUpdates} entries.`);
        }
        const pushTo = flags['push-to'];
        if (!pushTo) {
            return { record, file, cwd };
        }
        const issueNumber = resolveIssueNumber(flags.ticket, taskId);
        if (!issueNumber) {
            this.warn('--ticket is required when using --push-to. Skipping write-back.');
            return { record, file, cwd };
        }
        const dryRun = flags['dry-run'];
        const evidenceRecords = listRecords(cwd, 'evidence').filter((e) => record.evidenceIds.includes(e.id));
        const decisionRecords = listRecords(cwd, 'decision').filter((d) => d.taskIds.includes(record.id));
        const payload = buildPayload(record, evidenceRecords.length, decisionRecords.map((d) => d.id));
        let writeBack;
        if (pushTo === 'github') {
            writeBack = await pushToGitHub(issueNumber, payload, dryRun);
        }
        else {
            writeBack = await pushToJira(issueNumber, payload, dryRun);
        }
        if (writeBack.dryRun) {
            this.log(messages.getMessage('info.writeBackDryRun', [pushTo]));
        }
        else if (writeBack.url) {
            this.log(messages.getMessage('info.writeBackPushed', [pushTo, writeBack.url]));
        }
        return { record, file, cwd, writeBack };
    }
}
function resolveIssueNumber(ticket, taskId) {
    if (ticket)
        return ticket;
    const match = /[A-Z]+-(\d+)/.exec(taskId);
    if (match) {
        const envVar = `GITHUB_ISSUE_${match[1]}`;
        const envValue = process.env[envVar];
        if (envValue)
            return envValue;
    }
    return null;
}
function buildPayload(record, evidenceCount, decisionIds) {
    const completedAt = record.updatedAt;
    const decisionList = decisionIds.length > 0 ? decisionIds.map((id) => `- ${id}`).join('\n') : '_none_';
    const body = [
        `## [setup-agents] Task ${record.id} done — ${record.summary}`,
        '',
        `**Status:** ${record.status}`,
        `**Owner:** ${record.owner ?? '_unassigned_'}`,
        `**Evidence count:** ${evidenceCount}`,
        `**Completed at:** ${completedAt}`,
        '',
        '### Linked Decisions',
        decisionList,
    ].join('\n');
    return {
        title: `[setup-agents] Task ${record.id} done — ${record.summary}`,
        body,
    };
}
//# sourceMappingURL=done.js.map