"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.runArchitectureReportGenerationForWorkspace = runArchitectureReportGenerationForWorkspace;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const projectIdentity_1 = require("./config/projectIdentity");
const discoverAdrs_1 = require("./discoverAdrs");
const governanceGitMetadata_1 = require("./governance/governanceGitMetadata");
const operationalLogging_1 = require("./operationalLogging");
const safetyControlsDetection_1 = require("./reporting/safetyControlsDetection");
const architectureReportArtifacts_1 = require("./reporting/architectureReportArtifacts");
const reviewGenerationWorkflow_1 = require("./reviewGenerationWorkflow");
async function readJsonFile(filePath) {
    try {
        return JSON.parse(await node_fs_1.promises.readFile(filePath, { encoding: 'utf8' }));
    }
    catch {
        return undefined;
    }
}
function normalizeValidationStatusExport(value) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return undefined;
    }
    const typed = value;
    if (!typed.summary ||
        typeof typed.summary !== 'object' ||
        !typed.dependencyGraphSummary ||
        typeof typed.dependencyGraphSummary !== 'object') {
        return undefined;
    }
    return typed;
}
function normalizeArchitectureDriftReport(value) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return undefined;
    }
    const typed = value;
    if (typeof typed.projectName !== 'string' ||
        typeof typed.generatedAtUtc !== 'string' ||
        typeof typed.baselineCreatedAtUtc !== 'string' ||
        !typed.summaryCounts ||
        typeof typed.summaryCounts !== 'object') {
        return undefined;
    }
    return typed;
}
async function runArchitectureReportGenerationForWorkspace(input) {
    (0, operationalLogging_1.emitOperationalMessage)(input.onOperationalMessage, 'info', 'Generating architecture reports from existing local artifacts.');
    const summaryLoaded = await (0, reviewGenerationWorkflow_1.readArchitectureReviewSummaryArtifact)(input.workspaceRoot);
    if (summaryLoaded.kind === 'missing') {
        throw new Error('Architecture summary artifact is missing. Run `archpilot validate` first to generate .archpilot/reports/architecture-summary.json.');
    }
    if (summaryLoaded.kind === 'invalid') {
        throw new Error(`Architecture summary artifact is invalid. ${summaryLoaded.details}\nRun \`archpilot validate\` to regenerate deterministic review artifacts.`);
    }
    const [healthTrendLoaded, validationStatusRaw, driftReportRaw, projectIdentityLoad, discoveredAdrs, gitMetadata] = await Promise.all([
        (0, reviewGenerationWorkflow_1.readValidationHealthTrend)(input.workspaceRoot),
        readJsonFile(path.join(input.workspaceRoot, '.archpilot', 'validation-status.json')),
        readJsonFile(path.join(input.workspaceRoot, '.archpilot', 'reports', 'architecture-drift.json')),
        (0, projectIdentity_1.readProjectIdentity)(input.workspaceRoot),
        (0, discoverAdrs_1.discoverAdrs)(input.workspaceRoot),
        (0, governanceGitMetadata_1.resolveGovernanceGitMetadata)(input.workspaceRoot),
    ]);
    if (projectIdentityLoad.invalidJson) {
        throw new Error(projectIdentityLoad.errorMessage ??
            'ArchPilot project identity config is invalid. Please fix .archpilot/project.json.');
    }
    const summaryForReport = {
        ...summaryLoaded.summary,
        safetyControls: await (0, safetyControlsDetection_1.detectMissingSafetyControls)({
            workspaceRoot: input.workspaceRoot,
            context: summaryLoaded.summary,
        }),
    };
    const validationStatus = normalizeValidationStatusExport(validationStatusRaw);
    const driftReport = normalizeArchitectureDriftReport(driftReportRaw);
    const healthTrend = healthTrendLoaded.kind === 'ok' ? healthTrendLoaded.healthTrend : undefined;
    const 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;
    const paths = await (0, architectureReportArtifacts_1.writeArchitectureReportArtifacts)({
        workspaceRoot: input.workspaceRoot,
        reviewSummary: summaryForReport,
        discoveredAdrs,
        suppressionSummary: validationStatus?.suppressionSummary,
        healthTrend,
        projectIdentity,
        dependencyGraphSummary: validationStatus?.dependencyGraphSummary,
        driftReport,
        driftDetected: validationStatus?.drift?.detected,
        commitSha: gitMetadata.commitSha,
    });
    (0, operationalLogging_1.emitOperationalMessage)(input.onOperationalMessage, 'info', 'Architecture report artifacts refreshed from existing local artifacts.');
    return { paths, summary: summaryForReport };
}
//# sourceMappingURL=architectureReportWorkflow.js.map