/*
 * 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 { spawnSync } from 'node:child_process';
import { SfError } from '@salesforce/core';
export function pushToGitHub(issueNumber, payload, dryRun, deps = {}) {
    if (dryRun) {
        const logFn = deps.log ??
            ((msg) => {
                process.stdout.write(`${msg}\n`);
            });
        logFn(`[dry-run] Would push to github (issue #${issueNumber}):`);
        logFn(`Title: ${payload.title}`);
        logFn(`Body:\n${payload.body}`);
        return Promise.resolve({ pushed: false, target: 'github', url: null, dryRun: true });
    }
    const spawnFn = deps.spawnSyncFn ??
        ((cmd, args, input) => {
            const result = spawnSync(cmd, args, { encoding: 'utf8', input });
            return {
                stdout: result.stdout ?? '',
                stderr: result.stderr ?? '',
                status: result.status,
            };
        });
    const result = spawnFn('gh', ['issue', 'comment', issueNumber, '--body-file', '-'], payload.body);
    if (result.status !== 0) {
        throw new SfError(result.stderr.trim() || `gh issue comment failed with status ${String(result.status)}`);
    }
    const url = parseGhUrl(result.stdout);
    return Promise.resolve({ pushed: true, target: 'github', url, dryRun: false });
}
export function pushToJira(issueKey, payload, dryRun, deps = {}) {
    if (dryRun) {
        const logFn = deps.log ??
            ((msg) => {
                process.stdout.write(`${msg}\n`);
            });
        logFn(`[dry-run] Would push to jira via MCP (issue ${issueKey}):`);
        logFn(`Title: ${payload.title}`);
        logFn(`Body:\n${payload.body}`);
        return Promise.resolve({ pushed: false, target: 'jira', url: null, dryRun: true });
    }
    const spawnFn = deps.spawnSyncFn ??
        ((cmd, args, input) => {
            const result = spawnSync(cmd, args, { encoding: 'utf8', input });
            return { stdout: result.stdout ?? '', stderr: result.stderr ?? '', status: result.status };
        });
    const comment = `${payload.title}\n\n${payload.body}`;
    const prompt = `Use the jira_add_comment MCP tool to add the following comment (provided via stdin) to issue ${issueKey}. The comment text is:\n${comment}`;
    const result = spawnFn('claude', ['--print', prompt, '--allowedTools', 'mcp__jira__jira_add_comment', '--output-format', 'json'], comment);
    if (result.status !== 0) {
        throw new SfError('Jira MCP write-back failed. Ensure the Atlassian MCP server is configured (sf setup-agents mcp). ' +
            (result.stderr.trim() || `Exit code: ${String(result.status)}`));
    }
    const url = parseJiraUrl(result.stdout, issueKey);
    return Promise.resolve({ pushed: true, target: 'jira', url, dryRun: false });
}
function parseJiraUrl(output, issueKey) {
    const urlMatch = /https:\/\/[^\s"]+\/browse\/[A-Z]+-\d+/.exec(output);
    if (urlMatch)
        return urlMatch[0];
    const siteMatch = /https:\/\/([^/\s"]+)\.atlassian\.net/.exec(output);
    if (siteMatch)
        return `https://${siteMatch[1]}.atlassian.net/browse/${issueKey}`;
    return null;
}
function parseGhUrl(output) {
    const match = /https:\/\/github\.com\/[^\s]+/.exec(output);
    return match ? match[0] : null;
}
//# sourceMappingURL=write-back.js.map