"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.readArchitectureReviewSummaryArtifact = readArchitectureReviewSummaryArtifact;
exports.readValidationHealthTrend = readValidationHealthTrend;
exports.runReviewGenerationForWorkspace = runReviewGenerationForWorkspace;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const discoverAdrs_1 = require("./discoverAdrs");
const projectIdentity_1 = require("./config/projectIdentity");
const operationalLogging_1 = require("./operationalLogging");
const architectureReviewReportGenerator_1 = require("./reporting/architectureReviewReportGenerator");
const safetyControlsDetection_1 = require("./reporting/safetyControlsDetection");
async function readJsonFile(filePath) {
    let contents;
    try {
        contents = await node_fs_1.promises.readFile(filePath, { encoding: 'utf8' });
    }
    catch (error) {
        if (error.code === 'ENOENT') {
            return { kind: 'missing' };
        }
        return {
            kind: 'invalid',
            details: error instanceof Error ? error.message : 'Unable to read JSON file.',
        };
    }
    try {
        return { kind: 'ok', value: JSON.parse(contents) };
    }
    catch {
        return { kind: 'invalid', details: 'Invalid JSON.' };
    }
}
function normalizeArchitectureReviewSummaryArtifact(value) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return undefined;
    }
    const typed = value;
    if (typeof typed.projectName !== 'string' || typeof typed.generatedAtUtc !== 'string') {
        return undefined;
    }
    return {
        ...typed,
        reportVersion: 1,
        healthScore: typeof typed.healthScore === 'number' ? typed.healthScore : 0,
        readinessScore: typeof typed.readinessScore === 'number' ? typed.readinessScore : 0,
        counts: typed.counts && typeof typed.counts === 'object'
            ? typed.counts
            : {
                errors: 0,
                warnings: 0,
                info: 0,
                passed: 0,
                suppressed: 0,
                ignoredSuppressions: 0,
            },
        findings: Array.isArray(typed.findings)
            ? typed.findings
            : [],
        passedChecks: Array.isArray(typed.passedChecks)
            ? typed.passedChecks
            : [],
        suppressedFindings: Array.isArray(typed.suppressedFindings)
            ? typed.suppressedFindings
            : [],
    };
}
async function readArchitectureReviewSummaryArtifact(workspaceRoot) {
    const summaryPath = path.join(workspaceRoot, '.archpilot', 'reports', 'architecture-summary.json');
    const loaded = await readJsonFile(summaryPath);
    if (loaded.kind === 'missing') {
        return { kind: 'missing' };
    }
    if (loaded.kind === 'invalid') {
        return { kind: 'invalid', details: loaded.details };
    }
    const normalized = normalizeArchitectureReviewSummaryArtifact(loaded.value);
    if (!normalized) {
        return { kind: 'invalid', details: 'Unexpected architecture summary shape.' };
    }
    return { kind: 'ok', summary: normalized };
}
async function readValidationHealthTrend(workspaceRoot) {
    const statusPath = path.join(workspaceRoot, '.archpilot', 'validation-status.json');
    const loaded = await readJsonFile(statusPath);
    if (loaded.kind !== 'ok') {
        return loaded;
    }
    if (!loaded.value || typeof loaded.value !== 'object' || Array.isArray(loaded.value)) {
        return { kind: 'invalid', details: 'Unexpected validation status shape.' };
    }
    const summary = loaded.value.summary;
    if (!summary || typeof summary !== 'object' || Array.isArray(summary)) {
        return { kind: 'invalid', details: 'Unexpected validation status summary shape.' };
    }
    const healthTrend = summary.healthTrend;
    if (!healthTrend || typeof healthTrend !== 'object' || Array.isArray(healthTrend)) {
        return { kind: 'ok' };
    }
    const typedTrend = healthTrend;
    if (typeof typedTrend.currentScore !== 'number' ||
        typeof typedTrend.trendDirection !== 'string') {
        return { kind: 'ok' };
    }
    return {
        kind: 'ok',
        healthTrend: typedTrend,
    };
}
async function runReviewGenerationForWorkspace(input) {
    (0, operationalLogging_1.emitOperationalMessage)(input.onOperationalMessage, 'info', 'Generating architecture review report from existing validation artifacts.');
    const summaryLoaded = await readArchitectureReviewSummaryArtifact(input.workspaceRoot);
    if (summaryLoaded.kind === 'missing') {
        throw new Error((0, architectureReviewReportGenerator_1.buildReviewGeneratePrerequisiteMessage)());
    }
    if (summaryLoaded.kind === 'invalid') {
        throw new Error(`Architecture review summary artifact is invalid. ${summaryLoaded.details}\nRun \`archpilot validate\` to regenerate deterministic review artifacts.`);
    }
    const healthTrendLoaded = await readValidationHealthTrend(input.workspaceRoot);
    if (healthTrendLoaded.kind === 'invalid') {
        (0, operationalLogging_1.emitOperationalMessage)(input.onOperationalMessage, 'warn', `Validation health trend artifact could not be read cleanly: ${healthTrendLoaded.details}`);
    }
    const projectIdentityLoad = await (0, projectIdentity_1.readProjectIdentity)(input.workspaceRoot);
    if (projectIdentityLoad.invalidJson) {
        throw new Error(projectIdentityLoad.errorMessage ??
            'ArchPilot project identity config is invalid. Please fix .archpilot/project.json.');
    }
    const discoveredAdrs = await (0, discoverAdrs_1.discoverAdrs)(input.workspaceRoot);
    const summaryForReport = {
        ...summaryLoaded.summary,
        safetyControls: await (0, safetyControlsDetection_1.detectMissingSafetyControls)({
            workspaceRoot: input.workspaceRoot,
            context: summaryLoaded.summary,
        }),
    };
    const reviewReportMarkdownPath = path.join(input.workspaceRoot, ...architectureReviewReportGenerator_1.architectureReviewReportMarkdownPathRelative.split('/'));
    const reviewReportJsonPath = path.join(input.workspaceRoot, ...architectureReviewReportGenerator_1.architectureReviewReportJsonPathRelative.split('/'));
    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 markdown = (0, architectureReviewReportGenerator_1.renderArchitectureReviewReportMarkdown)({
        summary: summaryForReport,
        ...(healthTrend ? { healthTrend } : {}),
        ...(projectIdentity ? { projectIdentity } : {}),
        discoveredAdrs,
    });
    const json = (0, architectureReviewReportGenerator_1.renderArchitectureReviewReportJson)({
        summary: summaryForReport,
        ...(healthTrend ? { healthTrend } : {}),
        ...(projectIdentity ? { projectIdentity } : {}),
        discoveredAdrs,
    });
    try {
        await node_fs_1.promises.mkdir(path.dirname(reviewReportMarkdownPath), { recursive: true });
        await Promise.all([
            node_fs_1.promises.writeFile(reviewReportMarkdownPath, markdown, { encoding: 'utf8' }),
            node_fs_1.promises.writeFile(reviewReportJsonPath, json, { encoding: 'utf8' }),
        ]);
    }
    catch (error) {
        throw new Error(error instanceof Error
            ? error.message
            : 'Unable to write architecture review report artifacts.');
    }
    (0, operationalLogging_1.emitOperationalMessage)(input.onOperationalMessage, 'info', `Architecture review report artifacts refreshed: ${architectureReviewReportGenerator_1.architectureReviewReportMarkdownPathRelative} and ${architectureReviewReportGenerator_1.architectureReviewReportJsonPathRelative}.`);
    return {
        summary: summaryForReport,
        markdown,
        json,
        reviewReportMarkdownPath,
        reviewReportJsonPath,
        ...(healthTrend ? { healthTrend } : {}),
    };
}
//# sourceMappingURL=reviewGenerationWorkflow.js.map