"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.runStandardValidationWorkflowForWorkspace = runStandardValidationWorkflowForWorkspace;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const architectureValidation_1 = require("./architectureValidation");
const remediationEngine_1 = require("./remediation/remediationEngine");
const architectureReviewReporter_1 = require("./reporting/architectureReviewReporter");
const discoverAdrs_1 = require("./discoverAdrs");
const impactAnalysisEngine_1 = require("./impactAnalysisEngine");
const riskPolicyConfig_1 = require("./policy/riskPolicyConfig");
const config_1 = require("./config");
const safetyControlsDetection_1 = require("./reporting/safetyControlsDetection");
const architectureGovernanceBaseline_1 = require("./architectureGovernanceBaseline");
const riskPolicyEnforcement_1 = require("./policy/riskPolicyEnforcement");
const adrRequirementStatus_1 = require("./adrRequirementStatus");
const architecturePrCommentReporter_1 = require("./reporting/architecturePrCommentReporter");
const operationalLogging_1 = require("./operationalLogging");
const governanceGitMetadata_1 = require("./governance/governanceGitMetadata");
const architectureReportArtifacts_1 = require("./reporting/architectureReportArtifacts");
function applyCanonicalValidationSummary(reviewSummary, validationSummary) {
    reviewSummary.healthScore = validationSummary.healthScore;
    reviewSummary.categoryScores = validationSummary.categoryScores;
    reviewSummary.readinessScore = validationSummary.readinessScore;
    reviewSummary.readinessCategoryScores = validationSummary.readinessCategoryScores;
    reviewSummary.setupGaps = validationSummary.setupGaps;
    reviewSummary.guidanceFindings = validationSummary.guidanceFindings;
    reviewSummary.qualityFindings = validationSummary.qualityFindings;
}
function buildEnforcementResult(risk, policyConfig, policyConfigSource, baselineComparison, policyConfigError) {
    const enforcementFromPolicy = (0, riskPolicyEnforcement_1.evaluateRiskPolicy)(risk, policyConfig, {
        thresholdSource: policyConfigSource === 'policy-file'
            ? 'policy-file'
            : policyConfigSource === 'fallback-default'
                ? 'fallback-default'
                : 'default',
        ...(baselineComparison ? { baselineStatus: baselineComparison.status } : {}),
    });
    if (policyConfigSource === 'default' && !policyConfigError) {
        return {
            ...enforcementFromPolicy,
            reasons: [
                'No local .archpilot/policy.json found. Using deterministic default policy configuration.',
                ...enforcementFromPolicy.reasons,
            ],
        };
    }
    if (!policyConfigError) {
        return enforcementFromPolicy;
    }
    return {
        ...enforcementFromPolicy,
        action: 'fail',
        policyLevel: 'fail',
        enforcementDecision: 'FAIL',
        ciExitBehavior: {
            blocking: true,
            exitCode: 1,
            reason: 'Policy configuration is invalid; enforcement falls back to blocking FAIL.',
        },
        reasons: [policyConfigError, ...enforcementFromPolicy.reasons],
        requiredActions: [
            'Fix .archpilot/policy.json to restore deterministic policy enforcement.',
            ...(enforcementFromPolicy.requiredActions ?? []),
        ],
    };
}
function buildAdrRequirementResult(reviewSummary, validationResults, workspaceRoot) {
    return (0, adrRequirementStatus_1.evaluateAdrRequirementStatus)(reviewSummary.enforcement, reviewSummary.risk, validationResults, workspaceRoot);
}
async function runStandardValidationWorkflowForWorkspace(input) {
    const phase = async (label, run) => {
        const started = Date.now();
        (0, operationalLogging_1.emitOperationalMessage)(input.onOperationalMessage, 'info', `${label}...`);
        try {
            return await run();
        }
        finally {
            (0, operationalLogging_1.emitOperationalMessage)(input.onOperationalMessage, 'info', `${label} completed in ${Date.now() - started}ms.`);
        }
    };
    (0, operationalLogging_1.emitOperationalMessage)(input.onOperationalMessage, 'info', 'Starting shared validation workflow.');
    const runResult = await phase('Running core architecture validation', () => (0, architectureValidation_1.runArchitectureValidationForWorkspace)(input.workspaceRoot, {
        openReportInEditor: input.openReportInEditor,
        onOperationalMessage: input.onOperationalMessage,
    }));
    const remediation = await phase('Building remediation suggestions', async () => ({
        fixSuggestions: (0, remediationEngine_1.buildFixSuggestions)(runResult.results),
        appliedFixes: [],
        remainingViolationsCount: runResult.results.filter((result) => !result.passed).length,
    }));
    const impactAnalysis = await phase('Generating impact analysis', async () => (0, impactAnalysisEngine_1.analyzeImpact)({
        graph: {
            modules: runResult.status.dependencyGraphSummary.modules
                .map((moduleSummary) => moduleSummary.module)
                .sort((left, right) => left.localeCompare(right)),
            edges: runResult.status.dependencyGraphSummary.modules.flatMap((moduleSummary) => (moduleSummary.actualDependencies.length > 0
                ? moduleSummary.actualDependencies
                : moduleSummary.declaredDependencies).map((target) => ({
                source: moduleSummary.module,
                target,
            }))),
        },
    }));
    const [riskPolicyLoad, discoveredAdrs, projectIdentityLoad, gitMetadata] = await phase('Loading report inputs', () => Promise.all([
        (0, riskPolicyConfig_1.readRiskPolicyConfig)(input.workspaceRoot),
        (0, discoverAdrs_1.discoverAdrs)(input.workspaceRoot),
        (0, config_1.readProjectIdentity)(input.workspaceRoot),
        (0, governanceGitMetadata_1.resolveGovernanceGitMetadata)(input.workspaceRoot),
    ]));
    const reviewSummary = (0, architectureReviewReporter_1.buildArchitectureReviewSummary)({
        projectName: runResult.config.projectName,
        results: runResult.results,
        suppressedResults: runResult.status.suppressedResults,
        ignoredSuppressionsCount: runResult.status.summary.ignoredSuppressions,
        changeSignals: {
            diffContextAvailable: false,
            impactAnalysis,
        },
    });
    const governanceBaseline = await phase('Loading governance baseline', () => (0, architectureGovernanceBaseline_1.readGovernanceBaseline)(input.workspaceRoot));
    const baselineComparison = (0, architectureGovernanceBaseline_1.compareWithGovernanceBaseline)(reviewSummary, governanceBaseline);
    reviewSummary.enforcement = buildEnforcementResult(reviewSummary.risk, riskPolicyLoad.config, riskPolicyLoad.source, baselineComparison, riskPolicyLoad.configError);
    reviewSummary.adrRequirement = buildAdrRequirementResult(reviewSummary, runResult.results, input.workspaceRoot);
    reviewSummary.safetyControls = await phase('Checking deployment safety controls', () => (0, safetyControlsDetection_1.detectMissingSafetyControls)({
        workspaceRoot: input.workspaceRoot,
        context: reviewSummary,
    }));
    reviewSummary.baselineComparison = baselineComparison;
    applyCanonicalValidationSummary(reviewSummary, runResult.status.summary);
    let baselineComparisonPath;
    try {
        baselineComparisonPath = await (0, architectureGovernanceBaseline_1.writeBaselineComparisonReport)(input.workspaceRoot, baselineComparison);
    }
    catch {
        baselineComparisonPath = undefined;
    }
    const reportArtifacts = await phase('Generating review and governance artifacts', () => (0, architectureReportArtifacts_1.writeArchitectureReportArtifacts)({
        workspaceRoot: input.workspaceRoot,
        reviewSummary,
        remediation,
        discoveredAdrs,
        suppressionSummary: runResult.status.suppressionSummary,
        healthTrend: runResult.status.summary.healthTrend,
        projectIdentity: projectIdentityLoad.identity
            ? {
                repositoryId: projectIdentityLoad.identity.repositoryId,
                ...(projectIdentityLoad.identity.organizationId
                    ? { organizationId: projectIdentityLoad.identity.organizationId }
                    : {}),
                ...(projectIdentityLoad.identity.team
                    ? { team: projectIdentityLoad.identity.team }
                    : {}),
                ...(projectIdentityLoad.identity.system
                    ? { system: projectIdentityLoad.identity.system }
                    : {}),
            }
            : undefined,
        dependencyGraphSummary: runResult.status.dependencyGraphSummary,
        driftDetected: runResult.status.drift.detected,
        commitSha: gitMetadata.commitSha,
    }));
    const impactAnalysisPath = path.join(input.workspaceRoot, '.archpilot', 'impact-analysis.json');
    await phase('Writing impact analysis artifact', async () => {
        await node_fs_1.promises.mkdir(path.dirname(impactAnalysisPath), { recursive: true });
        await node_fs_1.promises.writeFile(impactAnalysisPath, `${JSON.stringify(reviewSummary.impactAnalysis, null, 2)}\n`, { encoding: 'utf8' });
    });
    let prCommentPath;
    if (input.ciMode) {
        const prCommentMarkdown = (0, architecturePrCommentReporter_1.renderArchitecturePrCommentMarkdown)({
            summary: reviewSummary,
            healthTrend: runResult.status.summary.healthTrend,
            driftComparison: runResult.status.driftComparison,
        });
        prCommentPath = await (0, architecturePrCommentReporter_1.writeArchitecturePrCommentMarkdown)(input.workspaceRoot, prCommentMarkdown);
    }
    (0, operationalLogging_1.emitOperationalMessage)(input.onOperationalMessage, 'info', 'Validation workflow finished and canonical validation/review artifacts were refreshed.');
    return {
        runResult,
        reviewSummary,
        remediation,
        reportArtifacts,
        impactAnalysisPath,
        baselineComparison,
        ...(baselineComparisonPath ? { baselineComparisonPath } : {}),
        ...(prCommentPath ? { prCommentPath } : {}),
    };
}
//# sourceMappingURL=validationWorkflow.js.map