/**
 * PR Comment - Pull Request Comment Formatting
 *
 * Generates and posts formatted comments on pull requests
 * with scan results and certification status.
 *
 * @module action/pr-comment
 */
/**
 * Comment marker for identifying Vaspera comments
 */
const COMMENT_MARKER = "<!-- vaspera-hardening-comment -->";
/**
 * Generate PR comment content from scan results
 */
export function generatePrComment(scanResult, context, certificationLevel) {
    const { bySeverity, totalFindings, scanners } = scanResult;
    // Title with badge
    const title = generateTitle(bySeverity, certificationLevel);
    // Summary section
    const summary = generateSummary(scanResult);
    // Findings table (top 20)
    const findingsTable = generateFindingsTable(scanResult);
    // Scanner status
    const scannerStatus = generateScannerStatus(scanners);
    // Certification badge if applicable
    const certificationBadge = certificationLevel
        ? generateCertificationBadge(certificationLevel)
        : undefined;
    // Footer
    const footer = generateFooter();
    return {
        title,
        summary,
        findingsTable,
        scannerStatus,
        certificationBadge,
        footer,
    };
}
/**
 * Generate full comment body
 */
export function formatCommentBody(content) {
    const sections = [
        COMMENT_MARKER,
        "",
        content.title,
        "",
        content.summary,
        "",
    ];
    if (content.certificationBadge) {
        sections.push(content.certificationBadge, "");
    }
    sections.push("## Scanner Results", "", content.scannerStatus, "");
    if (content.findingsTable) {
        sections.push("## Top Findings", "", content.findingsTable, "");
    }
    sections.push(content.footer);
    return sections.join("\n");
}
/**
 * Generate title with status icon
 */
function generateTitle(bySeverity, certificationLevel) {
    const hasCritical = bySeverity.critical > 0;
    const hasHigh = bySeverity.high > 0;
    let icon;
    let status;
    if (certificationLevel) {
        switch (certificationLevel) {
            case "certified":
                icon = "✅";
                status = "Certified";
                break;
            case "approved":
                icon = "🟢";
                status = "Approved";
                break;
            case "review_required":
                icon = "🟡";
                status = "Review Required";
                break;
            case "blocked":
                icon = "🔴";
                status = "Blocked";
                break;
            default:
                icon = "📊";
                status = "Scanned";
        }
    }
    else if (hasCritical) {
        icon = "🔴";
        status = "Critical Issues Found";
    }
    else if (hasHigh) {
        icon = "🟠";
        status = "High Severity Issues Found";
    }
    else if (bySeverity.medium > 0) {
        icon = "🟡";
        status = "Medium Severity Issues Found";
    }
    else if (bySeverity.low > 0 || bySeverity.info > 0) {
        icon = "🟢";
        status = "Low Severity Issues Found";
    }
    else {
        icon = "✅";
        status = "No Issues Found";
    }
    return `# ${icon} Vaspera Hardening: ${status}`;
}
/**
 * Generate summary section
 */
function generateSummary(scanResult) {
    const { bySeverity, totalFindings, totalDuration } = scanResult;
    const lines = [
        "### Summary",
        "",
        `| Severity | Count |`,
        `|----------|-------|`,
        `| 🔴 Critical | ${bySeverity.critical} |`,
        `| 🟠 High | ${bySeverity.high} |`,
        `| 🟡 Medium | ${bySeverity.medium} |`,
        `| 🔵 Low | ${bySeverity.low} |`,
        `| ⚪ Info | ${bySeverity.info} |`,
        `| **Total** | **${totalFindings}** |`,
        "",
        `⏱️ Scan completed in ${(totalDuration / 1000).toFixed(1)}s`,
    ];
    return lines.join("\n");
}
/**
 * Generate scanner status table
 */
function generateScannerStatus(scanners) {
    const lines = [
        "| Scanner | Findings | Status | Duration |",
        "|---------|----------|--------|----------|",
    ];
    for (const scanner of scanners) {
        const status = scanner.success ? "✅" : `❌ ${scanner.error?.slice(0, 30) || "Failed"}`;
        const duration = `${(scanner.duration / 1000).toFixed(1)}s`;
        lines.push(`| ${scanner.scanner} | ${scanner.findings.length} | ${status} | ${duration} |`);
    }
    return lines.join("\n");
}
/**
 * Generate findings table (top 20 critical/high)
 */
function generateFindingsTable(scanResult) {
    const allFindings = [];
    for (const scanner of scanResult.scanners) {
        allFindings.push(...scanner.findings);
    }
    // Sort by severity (critical first, then high)
    const severityOrder = {
        critical: 5,
        high: 4,
        medium: 3,
        low: 2,
        info: 1,
    };
    allFindings.sort((a, b) => severityOrder[b.severity] - severityOrder[a.severity]);
    // Take top 20
    const topFindings = allFindings.slice(0, 20);
    if (topFindings.length === 0) {
        return "_No findings to display_";
    }
    const lines = [
        "<details>",
        "<summary>Click to expand findings</summary>",
        "",
        "| Severity | File | Line | Message | Scanner |",
        "|----------|------|------|---------|---------|",
    ];
    for (const finding of topFindings) {
        const severityIcon = getSeverityIcon(finding.severity);
        const shortMessage = finding.message.slice(0, 50) + (finding.message.length > 50 ? "..." : "");
        const shortFile = finding.file.length > 30
            ? "..." + finding.file.slice(-27)
            : finding.file;
        lines.push(`| ${severityIcon} ${finding.severity} | \`${shortFile}\` | ${finding.line} | ${shortMessage} | ${finding.scanner} |`);
    }
    lines.push("", "</details>");
    if (allFindings.length > 20) {
        lines.push("", `_...and ${allFindings.length - 20} more findings_`);
    }
    return lines.join("\n");
}
/**
 * Get icon for severity level
 */
function getSeverityIcon(severity) {
    switch (severity) {
        case "critical":
            return "🔴";
        case "high":
            return "🟠";
        case "medium":
            return "🟡";
        case "low":
            return "🔵";
        case "info":
            return "⚪";
        default:
            return "⚪";
    }
}
/**
 * Generate certification badge
 */
function generateCertificationBadge(level) {
    let badge;
    let description;
    switch (level) {
        case "certified":
            badge = "![Certified](https://img.shields.io/badge/Vaspera-Certified-brightgreen)";
            description = "This codebase has passed all security checks and is certified for production.";
            break;
        case "approved":
            badge = "![Approved](https://img.shields.io/badge/Vaspera-Approved-green)";
            description = "This codebase has passed security review with minor issues noted.";
            break;
        case "review_required":
            badge = "![Review Required](https://img.shields.io/badge/Vaspera-Review_Required-yellow)";
            description = "This codebase requires manual review before production deployment.";
            break;
        case "blocked":
            badge = "![Blocked](https://img.shields.io/badge/Vaspera-Blocked-red)";
            description = "This codebase has critical issues that must be resolved before deployment.";
            break;
        default:
            return "";
    }
    return `### Certification Status\n\n${badge}\n\n${description}`;
}
/**
 * Generate footer
 */
function generateFooter() {
    return `---
_Generated by [Vaspera Hardening](https://github.com/RCOLKITT/hardening-mcp) • [View full report](https://github.com/RCOLKITT/hardening-mcp#readme)_`;
}
/**
 * Find existing Vaspera comment on PR
 */
export async function findExistingComment(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
octokit, context) {
    if (!context.pullRequest)
        return null;
    const response = await octokit.rest.issues.listComments({
        owner: context.owner,
        repo: context.repo,
        issue_number: context.pullRequest.number,
        per_page: 100,
    });
    for (const comment of response.data) {
        if (comment.body?.includes(COMMENT_MARKER)) {
            return comment.id;
        }
    }
    return null;
}
/**
 * Create or update PR comment
 */
export async function postPrComment(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
octokit, context, body) {
    if (!context.pullRequest) {
        throw new Error("Cannot post PR comment: not a pull request event");
    }
    const existingId = await findExistingComment(octokit, context);
    if (existingId) {
        // Update existing comment
        const response = await octokit.rest.issues.updateComment({
            owner: context.owner,
            repo: context.repo,
            comment_id: existingId,
            body,
        });
        return { id: response.data.id, url: response.data.html_url };
    }
    else {
        // Create new comment
        const response = await octokit.rest.issues.createComment({
            owner: context.owner,
            repo: context.repo,
            issue_number: context.pullRequest.number,
            body,
        });
        return { id: response.data.id, url: response.data.html_url };
    }
}
//# sourceMappingURL=pr-comment.js.map