/**
 * pipeline/release-report.ts
 *
 * Cross-area release impact reports.
 *
 * Phase 4c of the Scenario Matrix implementation.
 *
 * Consolidates impact data from multi-area content releases into a single
 * report that combines document classification (4a), before/after deltas (2b),
 * attribution (2c), and probe results (4b) into the document × area × task
 * impact matrix specified by Scenario 2.4.
 *
 * @see docs/archive/exec-plans/scenario-matrix-implementation/phase-4-content-release-integration.md
 */
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
 * Build a cross-area release impact report.
 *
 * Combines classification, comparison, attribution, and probe data into
 * a single consolidated report.
 *
 * @param classification - Document classification from Phase 4a
 * @param comparison - Before/after comparison (if available)
 * @param attribution - Per-document attribution (if available)
 * @param probes - Tier B probe results (if any)
 * @param noiseThreshold - Threshold for "unchanged" classification
 * @returns Consolidated release impact report
 */
export function buildReleaseImpactReport(classification, comparison, attribution, probes, noiseThreshold) {
    const threshold = noiseThreshold ?? comparison?.noiseThreshold ?? 2;
    // Build per-area impact from comparison data
    const areas = [];
    const regressions = [];
    const confirmedUnchanged = [];
    if (comparison) {
        for (const areaDelta of comparison.areas) {
            // Skip areas that weren't evaluated in both runs — these are
            // mismatched areas (e.g., auto-scoped release eval vs full baseline).
            if (areaDelta.change === "not-evaluated")
                continue;
            const regressed = areaDelta.delta < -threshold;
            // Find tasks and their attributed documents for this area
            const areaTasks = [];
            if (attribution) {
                const areaAttrs = attribution.attributions.filter((a) => a.area === areaDelta.area);
                for (const attr of areaAttrs) {
                    areaTasks.push({
                        attributedDocs: attr.attributedDocs,
                        delta: attr.delta,
                        taskId: attr.taskId,
                    });
                }
            }
            // If no attribution data, create a single task entry per area
            if (areaTasks.length === 0) {
                areaTasks.push({
                    attributedDocs: [],
                    delta: areaDelta.delta,
                    taskId: `${areaDelta.area} (area-level)`,
                });
            }
            areas.push({
                area: areaDelta.area,
                delta: areaDelta.delta,
                regressed,
                tasks: areaTasks,
            });
            if (regressed) {
                regressions.push(areaDelta.area);
            }
            if (Math.abs(areaDelta.delta) <= threshold) {
                confirmedUnchanged.push(areaDelta.area);
            }
        }
    }
    // Determine which areas were not evaluated
    const evaluatedAreas = new Set(areas.map((a) => a.area));
    const allAffectedAreas = new Set(classification.documents.flatMap((d) => d.affectedAreas));
    const notEvaluated = [...allAffectedAreas]
        .filter((a) => !evaluatedAreas.has(a))
        .sort();
    // Calculate overall delta
    const overallDelta = comparison ? comparison.deltas.overall : 0;
    return {
        areas,
        confirmedUnchanged,
        documents: classification.documents,
        generatedAt: new Date().toISOString(),
        notEvaluated,
        overallDelta,
        probes: probes ?? [],
        regressions,
    };
}
// ---------------------------------------------------------------------------
// Formatting
// ---------------------------------------------------------------------------
/**
 * Format a release impact report for console output.
 */
export function formatReleaseImpactConsole(report) {
    const lines = [];
    lines.push("═══════════════════════════════════════════════════════════════");
    lines.push(" CONTENT RELEASE IMPACT REPORT");
    lines.push("═══════════════════════════════════════════════════════════════");
    lines.push("");
    const deltaStr = report.overallDelta >= 0
        ? `+${report.overallDelta.toFixed(1)}`
        : report.overallDelta.toFixed(1);
    lines.push(`  Overall impact: ${deltaStr} points`);
    lines.push(`  Documents: ${report.documents.length}`);
    lines.push(`  Areas affected: ${report.areas.length}`);
    lines.push("");
    // Regressions
    if (report.regressions.length > 0) {
        lines.push("  ⚠️  REGRESSIONS DETECTED:");
        for (const area of report.regressions) {
            const areaData = report.areas.find((a) => a.area === area);
            if (areaData) {
                lines.push(`    ${area}: ${areaData.delta.toFixed(1)}`);
            }
        }
        lines.push("");
    }
    // Impact matrix
    if (report.areas.length > 0) {
        lines.push("  Document                        | Area             | Task                    | Delta");
        lines.push("  ────────────────────────────────┼──────────────────┼─────────────────────────┼──────");
        for (const area of report.areas) {
            for (const task of area.tasks) {
                const docs = task.attributedDocs.length > 0
                    ? task.attributedDocs.join(", ")
                    : "(unattributed)";
                const taskDeltaStr = task.delta >= 0 ? `+${task.delta.toFixed(1)}` : task.delta.toFixed(1);
                lines.push(`  ${docs.padEnd(32)} | ${area.area.padEnd(16)} | ${task.taskId.padEnd(23)} | ${taskDeltaStr}`);
            }
        }
        lines.push("");
    }
    // Probe results
    if (report.probes.length > 0) {
        lines.push("  TIER B PROBES (directional only):");
        for (const probe of report.probes) {
            lines.push(`    ${probe.documentSlugs.join(", ")}: ${probe.usability}`);
        }
        lines.push("");
    }
    // Unchanged and not-evaluated areas
    if (report.confirmedUnchanged.length > 0) {
        lines.push(`  Areas with no score change: ${report.confirmedUnchanged.join(", ")}`);
    }
    if (report.notEvaluated.length > 0) {
        lines.push(`  Areas not evaluated: ${report.notEvaluated.join(", ")}`);
    }
    if (report.confirmedUnchanged.length > 0 || report.notEvaluated.length > 0) {
        lines.push("");
    }
    return lines.join("\n");
}
/**
 * Format a release impact report as markdown.
 */
export function formatReleaseImpactMarkdown(report) {
    const lines = [];
    lines.push("### 📋 Content Release Impact Report");
    lines.push("");
    const deltaStr = report.overallDelta >= 0
        ? `+${report.overallDelta.toFixed(1)}`
        : report.overallDelta.toFixed(1);
    lines.push(`**Overall impact: ${deltaStr} points** · ${report.documents.length} documents · ${report.areas.length} areas`);
    lines.push("");
    // Regressions
    if (report.regressions.length > 0) {
        lines.push("#### ⚠️ Regressions");
        lines.push("");
        for (const area of report.regressions) {
            const areaData = report.areas.find((a) => a.area === area);
            if (areaData) {
                lines.push(`- **${area}**: ${areaData.delta.toFixed(1)}`);
            }
        }
        lines.push("");
    }
    // Impact table
    if (report.areas.length > 0) {
        lines.push("#### Impact Matrix");
        lines.push("");
        lines.push("| Document | Area | Task | Delta |");
        lines.push("|----------|------|------|-------|");
        for (const area of report.areas) {
            for (const task of area.tasks) {
                const docs = task.attributedDocs.length > 0
                    ? task.attributedDocs.map((d) => `\`${d}\``).join(", ")
                    : "—";
                const taskDeltaStr = task.delta >= 0 ? `+${task.delta.toFixed(1)}` : task.delta.toFixed(1);
                const regressIcon = area.regressed ? " ⚠️" : "";
                lines.push(`| ${docs} | ${area.area} | ${task.taskId} | ${taskDeltaStr}${regressIcon} |`);
            }
        }
        lines.push("");
    }
    // Probes
    if (report.probes.length > 0) {
        lines.push("#### 🔍 Tier B Probes (directional only)");
        lines.push("");
        for (const probe of report.probes) {
            lines.push(`- **${probe.documentSlugs.join(", ")}**: ${probe.usability}`);
        }
        lines.push("");
    }
    // Status areas
    const statusParts = [];
    if (report.confirmedUnchanged.length > 0) {
        statusParts.push(`**Unchanged:** ${report.confirmedUnchanged.join(", ")}`);
    }
    if (report.notEvaluated.length > 0) {
        statusParts.push(`**Not evaluated:** ${report.notEvaluated.join(", ")}`);
    }
    if (statusParts.length > 0) {
        lines.push(statusParts.join(" · "));
        lines.push("");
    }
    return lines.join("\n");
}
