/**
 * Comment Builder for External Tool Sync
 *
 * Generates formatted comments for posting to external tools
 * (GitHub, JIRA, Azure DevOps) with commit/PR links and summaries.
 */
/**
 * Build comment for completed user story
 */
export function buildUserStoryComment(content, repo) {
    const { userStory, tasks, commits, pullRequests } = content;
    // Build markdown comment
    let markdown = `## ✅ ${userStory.id}: ${userStory.title}\n\n`;
    // Add summary
    if (content.summary) {
        markdown += `${content.summary}\n\n`;
    }
    // Add completed tasks
    if (tasks.length > 0) {
        markdown += `**Completed Tasks:**\n`;
        for (const task of tasks) {
            markdown += `- ${task.id}: ${task.title}\n`;
        }
        markdown += '\n';
    }
    // Add commits
    if (commits.length > 0) {
        markdown += `**Commits:**\n`;
        for (const commit of commits) {
            const url = commit.url || `${repo.url}/commit/${commit.sha}`;
            const shortMsg = commit.message.split('\n')[0].substring(0, 60);
            markdown += `- [\`${commit.shortSha}\`](${url}) ${shortMsg}\n`;
        }
        markdown += '\n';
    }
    // Add pull requests
    if (pullRequests.length > 0) {
        markdown += `**Pull Requests:**\n`;
        for (const pr of pullRequests) {
            markdown += `- [#${pr.number}](${pr.url}) ${pr.title} (${pr.state})\n`;
        }
        markdown += '\n';
    }
    // Add acceptance criteria
    const completedACs = userStory.acceptanceCriteria.filter(ac => ac.completed);
    if (completedACs.length > 0) {
        markdown += `**Acceptance Criteria:**\n`;
        for (const ac of completedACs) {
            markdown += `- ✓ ${ac.id}: ${ac.description}\n`;
        }
        markdown += '\n';
    }
    markdown += `---\n🤖 _Auto-generated by SpecWeave_`;
    return {
        markdown,
        plain: markdownToPlainText(markdown),
    };
}
/**
 * Build short summary comment (for quick updates)
 */
export function buildShortComment(commits, repo, summary) {
    let markdown = '';
    if (summary) {
        markdown += `${summary}\n\n`;
    }
    if (commits.length > 0) {
        markdown += `**Commits:**\n`;
        for (const commit of commits) {
            const url = commit.url || `${repo.url}/commit/${commit.sha}`;
            const shortMsg = commit.message.split('\n')[0].substring(0, 60);
            markdown += `- [\`${commit.shortSha}\`](${url}) ${shortMsg}\n`;
        }
    }
    markdown += `\n---\n🤖 _Auto-generated by SpecWeave_`;
    return {
        markdown,
        plain: markdownToPlainText(markdown),
    };
}
/**
 * Build comment for multiple commits (batch update)
 */
export function buildCommitBatchComment(commits, repo, groupByDate = true) {
    let markdown = `## 🔄 Recent Updates\n\n`;
    if (groupByDate) {
        // Group commits by date
        const commitsByDate = new Map();
        for (const commit of commits) {
            const dateKey = commit.date.toISOString().split('T')[0];
            if (!commitsByDate.has(dateKey)) {
                commitsByDate.set(dateKey, []);
            }
            commitsByDate.get(dateKey).push(commit);
        }
        // Sort dates descending
        const sortedDates = Array.from(commitsByDate.keys()).sort().reverse();
        for (const date of sortedDates) {
            markdown += `### ${date}\n\n`;
            const dateCommits = commitsByDate.get(date);
            for (const commit of dateCommits) {
                const url = commit.url || `${repo.url}/commit/${commit.sha}`;
                const shortMsg = commit.message.split('\n')[0].substring(0, 60);
                markdown += `- [\`${commit.shortSha}\`](${url}) ${shortMsg} _by ${commit.author}_\n`;
            }
            markdown += '\n';
        }
    }
    else {
        // Simple list
        for (const commit of commits) {
            const url = commit.url || `${repo.url}/commit/${commit.sha}`;
            const shortMsg = commit.message.split('\n')[0].substring(0, 60);
            markdown += `- [\`${commit.shortSha}\`](${url}) ${shortMsg}\n`;
        }
        markdown += '\n';
    }
    markdown += `---\n🤖 _Auto-generated by SpecWeave_`;
    return {
        markdown,
        plain: markdownToPlainText(markdown),
    };
}
/**
 * Build comment for PR merge
 */
export function buildPRMergeComment(pr, commits, repo) {
    let markdown = `## 🎉 Merged: [#${pr.number}](${pr.url})\n\n`;
    markdown += `${pr.title}\n\n`;
    if (commits.length > 0) {
        markdown += `**Commits (${commits.length}):**\n`;
        for (const commit of commits.slice(0, 10)) { // Limit to 10
            const url = commit.url || `${repo.url}/commit/${commit.sha}`;
            const shortMsg = commit.message.split('\n')[0].substring(0, 60);
            markdown += `- [\`${commit.shortSha}\`](${url}) ${shortMsg}\n`;
        }
        if (commits.length > 10) {
            markdown += `\n_...and ${commits.length - 10} more commits_\n`;
        }
        markdown += '\n';
    }
    markdown += `---\n🤖 _Auto-generated by SpecWeave_`;
    return {
        markdown,
        plain: markdownToPlainText(markdown),
    };
}
/**
 * Generate smart summary from commits
 */
export function generateSmartSummary(commits, tasks) {
    if (commits.length === 0) {
        return 'Work completed';
    }
    // Analyze commit messages for common patterns
    const messages = commits.map(c => c.message.toLowerCase());
    const patterns = {
        feat: messages.filter(m => m.startsWith('feat:')).length,
        fix: messages.filter(m => m.startsWith('fix:')).length,
        docs: messages.filter(m => m.startsWith('docs:')).length,
        refactor: messages.filter(m => m.startsWith('refactor:')).length,
        test: messages.filter(m => m.startsWith('test:')).length,
        chore: messages.filter(m => m.startsWith('chore:')).length,
    };
    const sortedPatterns = Object.entries(patterns)
        .filter(([_, count]) => count > 0)
        .sort(([_, a], [__, b]) => b - a);
    if (sortedPatterns.length === 0) {
        return `Completed ${tasks.length} task(s) with ${commits.length} commit(s)`;
    }
    const [topPattern, topCount] = sortedPatterns[0];
    const patternNames = {
        feat: 'New features',
        fix: 'Bug fixes',
        docs: 'Documentation updates',
        refactor: 'Code refactoring',
        test: 'Test improvements',
        chore: 'Maintenance work',
    };
    return `${patternNames[topPattern]} (${topCount} commit${topCount > 1 ? 's' : ''})`;
}
/**
 * Convert markdown to plain text (strip markdown formatting)
 */
function markdownToPlainText(markdown) {
    return markdown
        .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') // Links
        .replace(/[*_`#]/g, '') // Formatting
        .replace(/---/g, '---') // Horizontal rules
        .replace(/\n{3,}/g, '\n\n'); // Multiple newlines
}
/**
 * Format comment for JIRA (converts markdown to JIRA markup)
 */
export function formatForJira(comment) {
    let jira = comment.markdown;
    // Convert markdown headers to JIRA
    jira = jira.replace(/^## (.+)$/gm, 'h2. $1');
    jira = jira.replace(/^### (.+)$/gm, 'h3. $1');
    // Convert markdown links to JIRA
    jira = jira.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '[$1|$2]');
    // Convert markdown code to JIRA
    jira = jira.replace(/`([^`]+)`/g, '{{$1}}');
    // Convert markdown lists to JIRA
    jira = jira.replace(/^- (.+)$/gm, '* $1');
    // Convert bold
    jira = jira.replace(/\*\*([^*]+)\*\*/g, '*$1*');
    // Convert italic
    jira = jira.replace(/\*([^*]+)\*/g, '_$1_');
    return jira;
}
/**
 * Format comment for Azure DevOps (HTML)
 */
export function formatForAdo(comment) {
    // Azure DevOps supports markdown in comments
    return comment.markdown;
}
/**
 * Validate comment size (some platforms have limits)
 */
export function validateCommentSize(comment, maxLength = 5000) {
    return comment.markdown.length <= maxLength;
}
/**
 * Truncate comment if too long
 */
export function truncateComment(comment, maxLength = 5000) {
    if (comment.markdown.length <= maxLength) {
        return comment;
    }
    const truncated = comment.markdown.substring(0, maxLength - 50);
    const markdown = truncated + '\n\n_...truncated_\n\n---\n🤖 _Auto-generated by SpecWeave_';
    return {
        markdown,
        plain: comment.plain ? comment.plain.substring(0, maxLength - 50) : undefined,
    };
}
//# sourceMappingURL=comment-builder.js.map