/**
 * pipeline/repo-eval-comment.ts
 *
 * Generates markdown PR comments for repo-based AILF evaluations.
 *
 * This is separate from the main pr-comment.ts (which generates the
 * internal AILF repo's PR comment). Repo eval comments are designed
 * for external teams and emphasize:
 *
 * - Documentation quality (not code quality)
 * - Per-task threshold pass/fail status
 * - Clear "what does this mean?" context
 * - skip-ailf bypass instructions
 *
 * @see docs/archive/exec-plans/tasks-as-content/phase-6-pr-quality-gates.md
 * @see packages/eval/src/pipeline/repo-threshold-evaluator.ts
 */
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
 * Generate a markdown PR comment for a repo-based evaluation.
 */
export function generateRepoEvalComment(options) {
    const { thresholdEval, scoreSummary, comparison, reportUrl, promptfooUrl, firstRun, } = options;
    const lines = [];
    // Comment marker for update-in-place
    lines.push("<!-- ailf-repo-eval-report -->");
    // Header
    const statusEmoji = thresholdEval.checkPassed ? "✅" : "⚠️";
    lines.push(`## 📊 AI Literacy Evaluation`);
    lines.push("");
    // Summary line
    lines.push(`${statusEmoji} Your team's documentation quality score is **${thresholdEval.overallScore}/100**` +
        (thresholdEval.defaultThreshold > 0
            ? ` (threshold: ${thresholdEval.defaultThreshold})`
            : "") +
        ". " +
        contextMessage(thresholdEval, comparison, firstRun));
    lines.push("");
    // Cost info
    const totalCost = scoreSummary.scores.reduce((sum, s) => sum + (s.totalCost ?? 0), 0);
    const graderCost = scoreSummary.overall.cost?.graderTotal ?? 0;
    const combinedCost = totalCost + graderCost;
    const testCount = scoreSummary.scores.reduce((sum, s) => sum + s.testCount, 0);
    const costStr = combinedCost > 0 ? ` · Cost: ${formatCost(combinedCost)}` : "";
    lines.push(`**Overall:** ${thresholdEval.overallScore}/100 · ` +
        `**Doc lift:** +${Math.round(scoreSummary.overall.avgDocLift)} points · ` +
        `${testCount} tests${costStr}`);
    lines.push("");
    // Per-task threshold table
    if (thresholdEval.results.length > 0) {
        lines.push("### Per-Task Results");
        lines.push("");
        lines.push("| Task | Score | Threshold | Status |");
        lines.push("|------|-------|-----------|--------|");
        for (const result of thresholdEval.results) {
            lines.push(`| ${result.taskId} | ${result.actualScore} | ${result.threshold} | ${statusIcon(result)} |`);
        }
        lines.push("");
    }
    // Dimension details (collapsible)
    const withDimensions = thresholdEval.results.filter((r) => r.dimensionResults && r.dimensionResults.length > 0);
    if (withDimensions.length > 0) {
        lines.push("<details>");
        lines.push("<summary>📊 Per-dimension breakdown</summary>");
        lines.push("");
        lines.push("| Task | Dimension | Score | Threshold | Status |");
        lines.push("|------|-----------|-------|-----------|--------|");
        for (const result of withDimensions) {
            for (const dim of result.dimensionResults) {
                lines.push(`| ${result.taskId} | ${dim.dimension} | ${dim.actual} | ${dim.threshold} | ${dim.passed ? "✅" : "❌"} |`);
            }
        }
        lines.push("");
        lines.push("</details>");
        lines.push("");
    }
    // Comparison section (when baseline exists)
    if (comparison && !firstRun) {
        const delta = comparison.deltas.overall;
        const direction = delta > 0 ? "up" : delta < 0 ? "down" : "unchanged";
        const arrow = delta > 0 ? "📈" : delta < 0 ? "📉" : "➡️";
        lines.push(`${arrow} Compared to last run: overall **${delta > 0 ? "+" : ""}${Math.round(delta)}** points (${direction}).`);
        lines.push("");
        if (comparison.regressed.length > 0) {
            lines.push(`> ⚠️ **Regressions detected:** ${comparison.regressed.map((a) => `\`${a}\``).join(", ")}`);
            lines.push("");
        }
    }
    // Score breakdown (collapsible)
    if (scoreSummary.scores.length > 0) {
        lines.push("<details>");
        lines.push("<summary>📋 Full score breakdown</summary>");
        lines.push("");
        lines.push("| Feature Area | Score | Task Completion | Code Correctness | Doc Coverage | Doc Lift |");
        lines.push("|-------------|-------|-----------------|------------------|-------------|----------|");
        const sorted = [...scoreSummary.scores].sort((a, b) => b.totalScore - a.totalScore);
        for (const s of sorted) {
            lines.push(`| ${s.feature} | **${Math.round(s.totalScore)}** | ${Math.round(s.taskCompletion)} | ${Math.round(s.codeCorrectness)} | ${Math.round(s.docCoverage)} | ${liftArrow(s.docLift)} |`);
        }
        lines.push("");
        lines.push("</details>");
        lines.push("");
    }
    // Footer with links and bypass instructions
    const links = [];
    if (reportUrl)
        links.push(`[View full report in Studio](${reportUrl})`);
    if (promptfooUrl)
        links.push(`[Detailed results](${promptfooUrl})`);
    if (links.length > 0) {
        lines.push(links.join(" · "));
        lines.push("");
    }
    lines.push(`> 💡 This check evaluates **documentation quality**, not code correctness. ` +
        `Add the \`skip-ailf\` label to bypass.`);
    lines.push("");
    // Timestamp
    const now = new Date();
    lines.push(`*Generated by [AI Literacy Framework](https://github.com/sanity-labs/ai-literacy-framework) · ${now.toUTCString()}*`);
    return lines.join("\n");
}
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
function contextMessage(eval_, comparison, firstRun) {
    if (firstRun) {
        return "This is the first evaluation for this task set. Future runs will show trends.";
    }
    if (eval_.checkPassed) {
        return "Documentation quality meets your team's bar.";
    }
    if (comparison) {
        return ("This reflects the current state of your product's documentation, " +
            "not changes in this PR.");
    }
    return ("Some tasks are below their configured thresholds. " +
        "Review the documentation for the affected areas.");
}
function statusIcon(result) {
    switch (result.status) {
        case "passed":
            return "✅ Pass";
        case "warning":
            return "⚠️ Below threshold";
        case "failed":
            return "❌ Blocked";
    }
}
function formatCost(cost) {
    if (cost === 0)
        return "$0.00";
    if (cost < 0.01)
        return `$${cost.toFixed(4)}`;
    return `$${cost.toFixed(2)}`;
}
function liftArrow(lift) {
    const rounded = Math.round(lift);
    if (rounded > 0)
        return `↑ +${rounded}`;
    if (rounded < 0)
        return `↓ ${rounded}`;
    return "→ 0";
}
