/**
 * GitHub Action Runner
 *
 * Runs Code Buddy as a GitHub Action for PR review, issue triage, and implementation.
 */
import { logger } from '../utils/logger.js';
// ============================================================================
// GitHubActionRunner
// ============================================================================
export class GitHubActionRunner {
    config = null;
    /**
     * Parse GitHub event payload into config
     */
    parseEvent(eventPayload) {
        const action = eventPayload.action;
        const repository = eventPayload.repository;
        const pullRequest = eventPayload.pull_request;
        const issue = eventPayload.issue;
        const repo = repository?.full_name || '';
        const token = process.env.GITHUB_TOKEN || process.env.INPUT_ANTHROPIC_API_KEY || '';
        let event = 'push';
        let mode = 'implement';
        let prNumber;
        let issueNumber;
        if (pullRequest) {
            event = 'pull_request';
            prNumber = pullRequest.number;
            mode = 'review';
        }
        else if (issue) {
            event = 'issues';
            issueNumber = issue.number;
            mode = 'triage';
        }
        else {
            event = 'push';
            mode = 'implement';
        }
        // Override mode from env if set
        const envMode = process.env.INPUT_MODE;
        if (envMode && ['review', 'triage', 'implement'].includes(envMode)) {
            mode = envMode;
        }
        this.config = { token, event, repo, prNumber, issueNumber, mode };
        logger.debug(`Parsed GitHub event: ${event}, mode: ${mode}, repo: ${repo}`);
        return this.config;
    }
    /**
     * Generate a structured review comment for a PR diff
     */
    generateReviewComment(diff, files) {
        const fileList = files.map(f => `- \`${f}\``).join('\n');
        const diffLines = diff.split('\n');
        const additions = diffLines.filter(l => l.startsWith('+')).length;
        const deletions = diffLines.filter(l => l.startsWith('-')).length;
        const comment = [
            '## Code Buddy AI Review',
            '',
            `**Files changed (${files.length}):**`,
            fileList,
            '',
            `**Changes:** +${additions} / -${deletions} lines`,
            '',
            '### Summary',
            '',
            'AI review of the changes in this pull request.',
            '',
            '### Suggestions',
            '',
            'No critical issues found.',
            '',
            '---',
            '*Generated by Code Buddy GitHub Action*',
        ].join('\n');
        return comment;
    }
    /**
     * Generate suggested labels for issue triage
     */
    generateTriageLabel(title, body) {
        const text = `${title} ${body}`.toLowerCase();
        const labels = [];
        if (text.includes('bug') || text.includes('error') || text.includes('crash') || text.includes('fix')) {
            labels.push('bug');
        }
        if (text.includes('feature') || text.includes('request') || text.includes('enhancement')) {
            labels.push('enhancement');
        }
        if (text.includes('doc') || text.includes('documentation') || text.includes('readme')) {
            labels.push('documentation');
        }
        if (text.includes('security') || text.includes('vulnerability') || text.includes('cve')) {
            labels.push('security');
        }
        if (text.includes('performance') || text.includes('slow') || text.includes('optimize')) {
            labels.push('performance');
        }
        if (text.includes('question') || text.includes('help') || text.includes('how to')) {
            labels.push('question');
        }
        if (labels.length === 0) {
            labels.push('needs-triage');
        }
        return labels;
    }
    /**
     * Format result for GitHub Actions output ($GITHUB_OUTPUT)
     */
    formatActionOutput(result) {
        const lines = [];
        for (const [key, value] of Object.entries(result)) {
            const stringValue = typeof value === 'string' ? value : JSON.stringify(value);
            // Handle multiline values with delimiter
            if (stringValue.includes('\n')) {
                lines.push(`${key}<<EOF`);
                lines.push(stringValue);
                lines.push('EOF');
            }
            else {
                lines.push(`${key}=${stringValue}`);
            }
        }
        return lines.join('\n');
    }
    /**
     * Generate the action.yml content
     */
    createActionYaml() {
        return `name: 'Code Buddy AI'
description: 'AI-powered code review, issue triage, and implementation'
inputs:
  anthropic_api_key:
    description: 'API key for the AI provider'
    required: true
  model:
    description: 'Model to use for AI tasks'
    required: false
    default: 'grok-3-mini'
  max_turns:
    description: 'Maximum number of agent turns'
    required: false
    default: '10'
  mode:
    description: 'Operation mode: review, triage, or implement'
    required: false
    default: 'review'
runs:
  using: 'node20'
  main: 'dist/action/index.js'
branding:
  icon: 'cpu'
  color: 'blue'
`;
    }
    /**
     * Get current config
     */
    getConfig() {
        return this.config;
    }
}
//# sourceMappingURL=github-action-runner.js.map