/**
 * Enterprise Certification System - Artifact Generation
 */
import { writeFile } from "fs/promises";
import { join } from "path";
import { CERTIFICATION_VALIDITY_DAYS, } from "./types.js";
import { generateBadgeSvg } from "./badge.js";
/**
 * Generate the CERTIFICATION.md report
 */
export function generateCertificationMarkdown(certification) {
    const { metadata, consensus, agents, red_team_challenges } = certification;
    if (!consensus) {
        throw new Error("Cannot generate artifact without consensus result");
    }
    const levelEmoji = {
        CERTIFIED: "🟢",
        APPROVED: "🟡",
        REVIEW_REQUIRED: "🟠",
        BLOCKED: "🔴",
    };
    const completedDate = metadata.completed_at
        ? new Date(metadata.completed_at).toLocaleDateString()
        : new Date().toLocaleDateString();
    const expiresDate = metadata.expires_at
        ? new Date(metadata.expires_at).toLocaleDateString()
        : "N/A";
    // Executive summary based on level
    const summaryByLevel = {
        CERTIFIED: "This codebase has passed comprehensive validation. All security, reliability, and quality checks meet high standards. No critical or high-severity issues were found, and the adversarial red team validation found no significant gaps.",
        APPROVED: "This codebase is approved for production deployment with monitoring. Minor issues were identified but no critical vulnerabilities exist. Review the high-priority recommendations before full deployment.",
        REVIEW_REQUIRED: "This codebase requires additional review before production deployment. Multiple issues were identified across security, reliability, or quality dimensions. Address the critical and high-severity findings before proceeding.",
        BLOCKED: "This codebase is BLOCKED from production deployment. Critical security vulnerabilities or fundamental reliability gaps were identified. Immediate remediation is required.",
    };
    // Build agent consensus table
    const agentRows = [];
    const allAgents = ["security", "reliability", "typesafety", "performance", "quality", "redteam"];
    for (const agent of allAgents) {
        const agentFindings = agents[agent];
        const score = consensus.agent_scores[agent] ?? "-";
        const confidence = consensus.agent_confidences[agent]
            ? `${Math.round(consensus.agent_confidences[agent])}%`
            : "-";
        let critical = 0, high = 0, medium = 0, low = 0;
        if (agentFindings) {
            for (const f of agentFindings.findings) {
                if (f.severity === "critical")
                    critical++;
                if (f.severity === "high")
                    high++;
                if (f.severity === "medium")
                    medium++;
                if (f.severity === "low")
                    low++;
            }
        }
        const agentDisplay = agent.charAt(0).toUpperCase() + agent.slice(1);
        agentRows.push(`| ${agentDisplay} | ${score} | ${confidence} | ${critical} | ${high} | ${medium} | ${low} |`);
    }
    // Collect critical findings
    const criticalFindings = [];
    const highFindings = [];
    for (const [agent, agentFindings] of Object.entries(agents)) {
        if (agentFindings) {
            for (const finding of agentFindings.findings) {
                if (finding.severity === "critical") {
                    criticalFindings.push({ agent, finding });
                }
                else if (finding.severity === "high") {
                    highFindings.push({ agent, finding });
                }
            }
        }
    }
    // Format findings
    const formatFinding = (agent, finding) => {
        const lines = [
            `#### ${finding.id}`,
            `- **Agent:** ${agent}`,
            `- **Category:** ${finding.category}`,
            finding.file ? `- **Location:** ${finding.file}${finding.line ? `:${finding.line}` : ""}` : "",
            `- **Confidence:** ${finding.confidence}%`,
            `- **Description:** ${finding.description}`,
            `- **Evidence:** ${finding.evidence}`,
        ];
        if (finding.verifications.length > 0) {
            lines.push(`- **Cross-verifications:**`);
            for (const v of finding.verifications) {
                lines.push(`  - ${v.verifying_agent}: ${v.verdict}`);
            }
        }
        return lines.filter((l) => l).join("\n");
    };
    // Format red team challenges
    const redTeamSection = red_team_challenges.length > 0
        ? red_team_challenges
            .map((c) => `- **${c.challenge_type}** targeting ${c.target_agent}: ${c.area}\n  - Evidence: ${c.evidence}\n  - Severity if valid: ${c.severity_if_valid}${c.resolution ? `\n  - Resolution: ${c.resolution.accepted ? "Accepted" : "Rejected"} - ${c.resolution.response}` : ""}`)
            .join("\n\n")
        : "No challenges raised by red team.";
    // Build the full report
    const markdown = `# Enterprise Certification Report

**Project:** ${metadata.project_name}
**Certification ID:** ${metadata.id}
**Date:** ${completedDate}
**Certification Level:** ${levelEmoji[consensus.certification_level]} ${consensus.certification_level}
**Overall Score:** ${consensus.overall_score}/100

---

## Executive Summary

${summaryByLevel[consensus.certification_level]}

## Certification Badge

\`\`\`
┌─────────────────────────────────────────────────┐
│  ${levelEmoji[consensus.certification_level]} ${consensus.certification_level.padEnd(20)} Score: ${consensus.overall_score}/100  │
│  Certified: ${completedDate.padEnd(12)} Valid Until: ${expiresDate}  │
│  ID: ${metadata.id.substring(0, 35).padEnd(35)}     │
└─────────────────────────────────────────────────┘
\`\`\`

---

## Agent Consensus

| Agent | Score | Confidence | Critical | High | Medium | Low |
|-------|-------|------------|----------|------|--------|-----|
${agentRows.join("\n")}

**Totals:** ${consensus.total_findings} findings (${consensus.by_severity.critical} critical, ${consensus.by_severity.high} high, ${consensus.by_severity.medium} medium, ${consensus.by_severity.low} low)

**Cross-verification Rate:** ${Math.round(consensus.cross_verification_rate * 100)}%

---

## Critical Findings (Must Fix)

${criticalFindings.length > 0
        ? criticalFindings.map(({ agent, finding }) => formatFinding(agent, finding)).join("\n\n")
        : "No critical findings."}

---

## High Priority Findings

${highFindings.length > 0
        ? highFindings.map(({ agent, finding }) => formatFinding(agent, finding)).join("\n\n")
        : "No high priority findings."}

---

## Red Team Challenges

${redTeamSection}

---

## Cross-Verification Summary

${consensus.cross_verification_rate > 0.8
        ? "Strong cross-verification coverage. Findings have been validated by multiple agents."
        : consensus.cross_verification_rate > 0.5
            ? "Moderate cross-verification coverage. Some findings lack validation."
            : "Low cross-verification coverage. Consider additional validation passes."}

---

## Recommendations

${generateRecommendations(consensus, certification)}

---

## Certification Validity

This certification is valid for ${CERTIFICATION_VALIDITY_DAYS} days from issuance date (until ${expiresDate}).

Re-certification is required after:
- Major code changes affecting security-critical paths
- Security incidents or vulnerability disclosures
- Significant dependency updates
- Changes to authentication or authorization logic

---

*Generated by Vaspera Enterprise Certification System v1.0*
*Certification ID: ${metadata.id}*
`;
    return markdown;
}
/**
 * Generate recommendations based on findings
 */
function generateRecommendations(consensus, certification) {
    const recommendations = [];
    // Critical findings
    if (consensus.by_severity.critical > 0) {
        recommendations.push(`1. **[CRITICAL] Fix all ${consensus.by_severity.critical} critical findings immediately.** These represent security vulnerabilities or crash risks.`);
    }
    // High findings
    if (consensus.by_severity.high > 0) {
        recommendations.push(`${recommendations.length + 1}. **[HIGH] Address ${consensus.by_severity.high} high-priority findings.** These will cause production issues.`);
    }
    // Low cross-verification
    if (consensus.cross_verification_rate < 0.5) {
        recommendations.push(`${recommendations.length + 1}. **Increase cross-verification coverage.** Current rate is ${Math.round(consensus.cross_verification_rate * 100)}%. Run additional agent passes.`);
    }
    // Red team challenges
    if (consensus.red_team_challenges_accepted > 0) {
        recommendations.push(`${recommendations.length + 1}. **Review accepted red team challenges.** ${consensus.red_team_challenges_accepted} challenges were validated.`);
    }
    // Agent-specific recommendations
    if (consensus.agent_scores.security !== undefined && consensus.agent_scores.security < 80) {
        recommendations.push(`${recommendations.length + 1}. **Improve security posture.** Security agent score is ${consensus.agent_scores.security}/100.`);
    }
    if (consensus.agent_scores.reliability !== undefined && consensus.agent_scores.reliability < 80) {
        recommendations.push(`${recommendations.length + 1}. **Enhance error handling.** Reliability agent score is ${consensus.agent_scores.reliability}/100.`);
    }
    if (consensus.agent_scores.typesafety !== undefined && consensus.agent_scores.typesafety < 70) {
        recommendations.push(`${recommendations.length + 1}. **Strengthen TypeScript usage.** Type safety score is ${consensus.agent_scores.typesafety}/100.`);
    }
    // Medium findings
    if (consensus.by_severity.medium > 10) {
        recommendations.push(`${recommendations.length + 1}. **Address medium-priority tech debt.** ${consensus.by_severity.medium} issues accumulating.`);
    }
    if (recommendations.length === 0) {
        recommendations.push("No immediate recommendations. Continue monitoring and maintain current standards.");
    }
    return recommendations.join("\n\n");
}
/**
 * Generate the CERTIFICATION.json file
 */
export function generateCertificationJson(certification) {
    return JSON.stringify({
        version: "1.0",
        metadata: certification.metadata,
        consensus: certification.consensus,
        summary: {
            level: certification.consensus?.certification_level,
            score: certification.consensus?.overall_score,
            findings: certification.consensus?.total_findings,
            by_severity: certification.consensus?.by_severity,
            valid_until: certification.metadata.expires_at,
        },
        agents: Object.entries(certification.agents).map(([name, data]) => ({
            name,
            score: certification.consensus?.agent_scores[name],
            confidence: certification.consensus?.agent_confidences[name],
            findings_count: data?.findings.length ?? 0,
        })),
    }, null, 2);
}
/**
 * Write certification artifacts to project
 */
export async function writeCertificationArtifacts(projectPath, certification) {
    const markdownPath = join(projectPath, "CERTIFICATION.md");
    const jsonPath = join(projectPath, "CERTIFICATION.json");
    const badgePath = join(projectPath, "certification-badge.svg");
    const markdown = generateCertificationMarkdown(certification);
    const json = generateCertificationJson(certification);
    await writeFile(markdownPath, markdown, "utf-8");
    await writeFile(jsonPath, json, "utf-8");
    // Generate badge if consensus exists
    if (certification.consensus) {
        const badge = generateBadgeSvg(certification.consensus.certification_level, certification.consensus.overall_score);
        await writeFile(badgePath, badge, "utf-8");
    }
    return { markdown: markdownPath, json: jsonPath, badge: badgePath };
}
//# sourceMappingURL=artifacts.js.map