import { SEVERITY_ORDER } from '../types/index.js';
import { countBySeverity } from '../cli/output/formatters.js';
import { escapeHtml } from '../utils/index.js';
const SEVERITY_EMOJI = {
    critical: ':rotating_light:',
    high: ':warning:',
    medium: ':orange_circle:',
    low: ':large_blue_circle:',
    info: ':information_source:',
};
/**
 * Render skill reports as a GitHub issue body.
 */
export function renderIssueBody(reports, options) {
    const { commitSha, runTimestamp, repoOwner, repoName } = options;
    const lines = [];
    // Header with timestamp and commit
    const shortSha = commitSha.slice(0, 7);
    const timestamp = runTimestamp.toISOString();
    lines.push('## Warden Scheduled Scan Results');
    lines.push('');
    lines.push(`**Run:** ${timestamp}`);
    lines.push(`**Commit:** \`${shortSha}\``);
    lines.push('');
    // Collect all findings
    const allFindings = reports.flatMap((r) => r.findings);
    if (allFindings.length === 0) {
        lines.push(':white_check_mark: **No issues found**');
        lines.push('');
        lines.push('The scheduled scan completed without finding any issues.');
        lines.push('');
        lines.push('---');
        lines.push('*Generated by [Warden](https://github.com/getsentry/warden)*');
        return lines.join('\n');
    }
    // Severity summary table
    const counts = countBySeverity(allFindings);
    lines.push('### Summary');
    lines.push('');
    lines.push('| Severity | Count |');
    lines.push('|----------|-------|');
    for (const severity of ['critical', 'high', 'medium', 'low', 'info']) {
        if (counts[severity] > 0) {
            lines.push(`| ${SEVERITY_EMOJI[severity]} ${severity} | ${counts[severity]} |`);
        }
    }
    lines.push('');
    // Findings grouped by file
    lines.push('### Findings');
    lines.push('');
    // Sort findings by severity, then by file
    const sortedFindings = [...allFindings].sort((a, b) => {
        const severityDiff = SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity];
        if (severityDiff !== 0)
            return severityDiff;
        const aPath = a.location?.path ?? '';
        const bPath = b.location?.path ?? '';
        return aPath.localeCompare(bPath);
    });
    const byFile = groupFindingsByFile(sortedFindings);
    const canLink = repoOwner && repoName;
    for (const [file, fileFindings] of Object.entries(byFile)) {
        if (canLink) {
            lines.push(`#### [\`${file}\`](https://github.com/${repoOwner}/${repoName}/blob/${commitSha}/${file})`);
        }
        else {
            lines.push(`#### \`${file}\``);
        }
        lines.push('');
        for (const finding of fileFindings) {
            lines.push(renderFindingItem(finding, { commitSha, repoOwner, repoName }));
        }
        lines.push('');
    }
    // General findings (no location)
    const noLocation = sortedFindings.filter((f) => !f.location);
    if (noLocation.length > 0) {
        lines.push('#### General');
        lines.push('');
        for (const finding of noLocation) {
            lines.push(renderFindingItem(finding, { commitSha, repoOwner, repoName }));
        }
        lines.push('');
    }
    // Per-skill summaries if multiple skills
    if (reports.length > 1) {
        lines.push('### Skill Summaries');
        lines.push('');
        for (const report of reports) {
            lines.push(`**${report.skill}:** ${escapeHtml(report.summary)}`);
            lines.push('');
        }
    }
    // Footer
    lines.push('---');
    lines.push('*Generated by [Warden](https://github.com/getsentry/warden)*');
    return lines.join('\n');
}
function groupFindingsByFile(findings) {
    const groups = {};
    for (const finding of findings) {
        if (finding.location) {
            const path = finding.location.path;
            groups[path] ??= [];
            groups[path].push(finding);
        }
    }
    return groups;
}
function formatLineRange(loc) {
    if (loc.endLine && loc.endLine !== loc.startLine) {
        return `L${loc.startLine}-L${loc.endLine}`;
    }
    return `L${loc.startLine}`;
}
function renderFindingItem(finding, ctx) {
    const { commitSha, repoOwner, repoName } = ctx;
    const canLink = repoOwner && repoName && finding.location;
    let locationStr = '';
    if (finding.location) {
        const lineRange = formatLineRange(finding.location);
        if (canLink) {
            const lineAnchor = finding.location.endLine
                ? `L${finding.location.startLine}-L${finding.location.endLine}`
                : `L${finding.location.startLine}`;
            locationStr = ` ([${lineRange}](https://github.com/${repoOwner}/${repoName}/blob/${commitSha}/${finding.location.path}#${lineAnchor}))`;
        }
        else {
            locationStr = ` (${lineRange})`;
        }
    }
    let line = `- ${SEVERITY_EMOJI[finding.severity]} **${escapeHtml(finding.title)}**${locationStr}`;
    line += `\n  ${escapeHtml(finding.description)}`;
    if (finding.suggestedFix) {
        line += `\n  *Suggested fix:* ${escapeHtml(finding.suggestedFix.description)}`;
    }
    return line;
}
/**
 * Render a brief status update for when no new findings are found.
 */
export function renderNoFindingsUpdate(commitSha, runTimestamp) {
    const shortSha = commitSha.slice(0, 7);
    const timestamp = runTimestamp.toISOString();
    return [
        '## Latest Scan: No Issues Found',
        '',
        `:white_check_mark: Scan completed at ${timestamp} (commit \`${shortSha}\`) with no issues.`,
        '',
        '---',
        '*Generated by [Warden](https://github.com/getsentry/warden)*',
    ].join('\n');
}
//# sourceMappingURL=issue-renderer.js.map