"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeArchitectureReportArtifacts = writeArchitectureReportArtifacts;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const architectureInit_1 = require("../architectureInit");
const architectureReviewReporter_1 = require("./architectureReviewReporter");
const architectureReviewReportGenerator_1 = require("./architectureReviewReportGenerator");
const architectureSupplementalReporters_1 = require("./architectureSupplementalReporters");
const managedArtifacts_1 = require("../managedArtifacts");
function buildImpactAnalysisSectionFromSummary(impactAnalysis) {
    const impactedContracts = impactAnalysis.affectedSurface?.impactedContracts ?? [];
    const impactedEntrypoints = impactAnalysis.affectedSurface?.impactedPublicEntrypoints ?? [];
    const impactedAdrs = impactAnalysis.affectedSurface?.impactedAdrs ?? [];
    const impactedArtifacts = impactAnalysis.affectedSurface?.impactedArchitectureArtifacts ?? [];
    const directChains = impactAnalysis.directDependencyChains && impactAnalysis.directDependencyChains.length > 0
        ? impactAnalysis.directDependencyChains.map((entry) => entry.chain.join(' -> ')).join(', ')
        : '(none)';
    const transitiveChains = impactAnalysis.transitiveDependencyChains &&
        impactAnalysis.transitiveDependencyChains.length > 0
        ? impactAnalysis.transitiveDependencyChains.map((entry) => entry.chain.join(' -> ')).join(', ')
        : '(none)';
    const factors = impactAnalysis.factors && impactAnalysis.factors.length > 0
        ? impactAnalysis.factors
            .map((factor) => `${factor.id} ${factor.label} (weight=${factor.weight})`)
            .join(', ')
        : '(none)';
    return `Changed Modules: ${impactAnalysis.changedModules.join(', ') || '(none)'}
Direct Dependents: ${impactAnalysis.directDependents.join(', ') || '(none)'}
Transitive Dependents: ${impactAnalysis.transitiveDependents.join(', ') || '(none)'}
Total Affected Modules: ${impactAnalysis.totalAffectedModules}
Impact Radius Score: ${impactAnalysis.impactRadiusScore}
Impact Level: ${impactAnalysis.impactLevel}
Summary: ${impactAnalysis.summary ?? '(none)'}
Impacted Contracts: ${impactedContracts.join(', ') || '(none)'}
Impacted Public Entrypoints: ${impactedEntrypoints.join(', ') || '(none)'}
Impacted ADRs: ${impactedAdrs.join(', ') || '(none)'}
Impacted Architecture Artifacts: ${impactedArtifacts.join(', ') || '(none)'}
Direct Dependency Chains: ${directChains}
Transitive Dependency Chains: ${transitiveChains}
Impact Factors: ${factors}
Scoring Formula: ${impactAnalysis.scoring?.formula ?? '(none)'}`;
}
async function readModulePaths(workspaceRoot) {
    try {
        const contract = await (0, architectureInit_1.loadArchitectureContract)(workspaceRoot);
        if (!contract) {
            return {};
        }
        return Object.fromEntries(Object.entries(contract.modules).map(([moduleName, entry]) => [moduleName, entry.path]));
    }
    catch {
        return {};
    }
}
async function writeArchitectureReportArtifacts(input) {
    const reportsDir = path.join(input.workspaceRoot, '.archpilot', 'reports');
    const reviewMarkdownPath = path.join(reportsDir, 'architecture-review.md');
    const reviewJsonPath = path.join(reportsDir, 'architecture-summary.json');
    const reviewCompactMarkdownPath = path.join(reportsDir, 'architecture-review-compact.md');
    const driftReportMarkdownPath = path.join(reportsDir, 'drift-report.md');
    const governanceReportMarkdownPath = path.join(reportsDir, 'governance-report.md');
    const reviewReportMarkdownPath = path.join(input.workspaceRoot, ...architectureReviewReportGenerator_1.architectureReviewReportMarkdownPathRelative.split('/'));
    const reviewReportJsonPath = path.join(input.workspaceRoot, ...architectureReviewReportGenerator_1.architectureReviewReportJsonPathRelative.split('/'));
    let reportWriteError;
    try {
        const modulePaths = await readModulePaths(input.workspaceRoot);
        const summaryMetadata = await (0, managedArtifacts_1.buildManagedMetadata)('validation-summary', input.reviewSummary.generatedAtUtc);
        await node_fs_1.promises.mkdir(reportsDir, { recursive: true });
        await Promise.all([
            node_fs_1.promises.writeFile(reviewMarkdownPath, (0, architectureReviewReporter_1.renderArchitectureReviewMarkdown)(input.reviewSummary, {
                impactAnalysisSection: buildImpactAnalysisSectionFromSummary(input.reviewSummary.impactAnalysis),
                remediation: input.remediation,
                discoveredAdrs: input.discoveredAdrs,
                suppressionSummary: input.suppressionSummary,
                dependencyGraphSummary: input.dependencyGraphSummary,
                modulePaths,
                driftReport: input.driftReport,
                commitSha: input.commitSha,
            }), { encoding: 'utf8' }),
            node_fs_1.promises.writeFile(reviewJsonPath, (0, architectureReviewReporter_1.renderArchitectureReviewJson)(input.reviewSummary, {
                metadata: summaryMetadata,
                remediation: input.remediation,
                suppressionSummary: input.suppressionSummary,
                dependencyGraphSummary: input.dependencyGraphSummary,
                driftReport: input.driftReport,
                driftDetected: input.driftDetected,
                commitSha: input.commitSha,
            }), { encoding: 'utf8' }),
            node_fs_1.promises.writeFile(reviewCompactMarkdownPath, (0, architectureReviewReporter_1.renderArchitectureReviewCompactMarkdown)(input.reviewSummary, {
                remediation: input.remediation,
            }), { encoding: 'utf8' }),
            node_fs_1.promises.writeFile(reviewReportMarkdownPath, (0, architectureReviewReportGenerator_1.renderArchitectureReviewReportMarkdown)({
                summary: input.reviewSummary,
                ...(input.healthTrend ? { healthTrend: input.healthTrend } : {}),
                ...(input.projectIdentity ? { projectIdentity: input.projectIdentity } : {}),
                discoveredAdrs: input.discoveredAdrs,
            }), { encoding: 'utf8' }),
            node_fs_1.promises.writeFile(reviewReportJsonPath, (0, architectureReviewReportGenerator_1.renderArchitectureReviewReportJson)({
                summary: input.reviewSummary,
                ...(input.healthTrend ? { healthTrend: input.healthTrend } : {}),
                ...(input.projectIdentity ? { projectIdentity: input.projectIdentity } : {}),
                discoveredAdrs: input.discoveredAdrs,
            }), { encoding: 'utf8' }),
            node_fs_1.promises.writeFile(driftReportMarkdownPath, (0, architectureSupplementalReporters_1.renderArchitectureDriftReportMarkdown)({
                summary: input.reviewSummary,
                driftReport: input.driftReport,
            }), { encoding: 'utf8' }),
            node_fs_1.promises.writeFile(governanceReportMarkdownPath, (0, architectureSupplementalReporters_1.renderArchitectureGovernanceReportMarkdown)({
                summary: input.reviewSummary,
                suppressionSummary: input.suppressionSummary,
                commitSha: input.commitSha,
            }), { encoding: 'utf8' }),
        ]);
    }
    catch (error) {
        reportWriteError =
            error instanceof Error
                ? error.message
                : 'Unable to write architecture review report artifacts.';
    }
    return {
        reviewMarkdownPath,
        reviewJsonPath,
        reviewCompactMarkdownPath,
        reviewReportMarkdownPath,
        reviewReportJsonPath,
        driftReportMarkdownPath,
        governanceReportMarkdownPath,
        ...(reportWriteError ? { reportWriteError } : {}),
    };
}
//# sourceMappingURL=architectureReportArtifacts.js.map