"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.populateReleaseInstallationReadme = populateReleaseInstallationReadme;
exports.populateReleaseInstallationReadmeFromBuildMetadata = populateReleaseInstallationReadmeFromBuildMetadata;
exports.populateReleaseDownloadBundle = populateReleaseDownloadBundle;
exports.copyStagedNoticeFilesToDownloadBundle = copyStagedNoticeFilesToDownloadBundle;
// Responsibility-focused extraction from output-lifecycle-installation-readme.ts.
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const cli_constants_1 = require("../../../lib/config/cli-constants");
const errors_1 = require("../../../lib/errors");
const output_lifecycle_checksums_1 = require("./output-lifecycle-checksums");
const output_lifecycle_output_state_1 = require("./output-lifecycle-output-state");
const output_lifecycle_staging_1 = require("./output-lifecycle-staging");
const output_lifecycle_installation_readme_rendering_1 = require("./output-lifecycle-installation-readme-rendering");
const output_lifecycle_installation_readme_validation_1 = require("./output-lifecycle-installation-readme-validation");
function populateReleaseInstallationReadme(options) {
    if (options.state.versionDirectory === null || options.state.versionDirectoryRelative === null) {
        throw (0, errors_1.createUsageError)('Release installation README requires a resolved version directory.', [
            'Exit behavior: exits before successful-release state is recorded.',
        ]);
    }
    const readmePath = node_path_1.default.join(options.state.versionDirectory, output_lifecycle_output_state_1.RELEASE_INSTALLATION_README_FILENAME);
    const readmePathRelative = `${options.state.versionDirectoryRelative}/${output_lifecycle_output_state_1.RELEASE_INSTALLATION_README_FILENAME}`;
    const markdown = (0, output_lifecycle_installation_readme_rendering_1.renderReleaseInstallationReadme)({
        metadata: (0, output_lifecycle_installation_readme_validation_1.createReleaseInstallationReadmeMetadataFromManifest)(options.manifest),
    });
    (0, output_lifecycle_installation_readme_validation_1.validateReleaseInstallationReadme)({
        markdown,
        manifest: options.manifest,
    });
    node_fs_1.default.writeFileSync(readmePath, markdown);
    return {
        status: 'written',
        path: readmePathRelative,
    };
}
function populateReleaseInstallationReadmeFromBuildMetadata(options) {
    if (options.state.versionDirectory === null || options.state.versionDirectoryRelative === null) {
        throw (0, errors_1.createUsageError)('Release installation README requires a resolved version directory.', [
            'Exit behavior: exits before successful-release state is recorded.',
        ]);
    }
    const metadata = (0, output_lifecycle_installation_readme_validation_1.createReleaseInstallationReadmeMetadataFromBuildMetadata)({
        state: options.state,
        version: options.version,
        packageName: options.packageName,
        installedCommandName: options.installedCommandName,
        requiredNodeVersion: options.requiredNodeVersion,
    });
    const bundleDirectory = (0, output_lifecycle_staging_1.resolveReleaseDownloadBundleDirectory)(options.state);
    const bundleDirectoryRelative = (0, output_lifecycle_staging_1.resolveReleaseDownloadBundleRelativeDirectory)(options.state);
    if (bundleDirectory === null || bundleDirectoryRelative === null) {
        throw (0, errors_1.createUsageError)('Release installation README requires a resolved download bundle directory.', [
            'Exit behavior: exits before successful-release state is recorded.',
        ]);
    }
    node_fs_1.default.mkdirSync(bundleDirectory, { recursive: true });
    const readmePath = node_path_1.default.join(bundleDirectory, output_lifecycle_output_state_1.RELEASE_INSTALLATION_README_FILENAME);
    const readmePathRelative = `${bundleDirectoryRelative}/${output_lifecycle_output_state_1.RELEASE_INSTALLATION_README_FILENAME}`;
    const markdown = (0, output_lifecycle_installation_readme_rendering_1.renderReleaseInstallationReadme)({ metadata });
    (0, output_lifecycle_installation_readme_validation_1.validateReleaseInstallationReadme)({
        markdown,
        metadata,
    });
    node_fs_1.default.writeFileSync(readmePath, markdown);
    return {
        status: 'written',
        path: readmePathRelative,
    };
}
function populateReleaseDownloadBundle(options) {
    if (options.state.versionDirectory === null || options.state.versionDirectoryRelative === null) {
        throw (0, errors_1.createUsageError)('Release download bundle requires a resolved version directory.', [
            'Exit behavior: exits before user download bundle files are created.',
        ]);
    }
    if (options.archivePayloads.status !== 'created' ||
        options.installerAssets.status !== 'created' ||
        options.artifactChecksums.status !== 'created' ||
        options.releaseManifest.status !== 'created' ||
        options.releaseManifest.manifestPath === null ||
        options.installationReadme.status !== 'written' ||
        options.installationReadme.path === null) {
        return (0, output_lifecycle_output_state_1.createNotApplicableDownloadBundle)();
    }
    const bundleDirectory = (0, output_lifecycle_staging_1.resolveReleaseDownloadBundleDirectory)(options.state);
    const bundleDirectoryRelative = (0, output_lifecycle_staging_1.resolveReleaseDownloadBundleRelativeDirectory)(options.state);
    if (bundleDirectory === null || bundleDirectoryRelative === null) {
        throw (0, errors_1.createUsageError)('Release download bundle requires a resolved download bundle directory.', [
            'Exit behavior: exits before user download bundle files are created.',
        ]);
    }
    const bundledNoticeArtifacts = copyStagedNoticeFilesToDownloadBundle({
        state: options.state,
        bundleDirectory,
        bundleDirectoryRelative,
        noticeFiles: options.noticeFiles ?? [],
    });
    const sourceArtifactPaths = [
        ...options.archivePayloads.targets.map((target) => target.archivePath),
        ...options.installerAssets.assets.map((asset) => asset.path),
        ...bundledNoticeArtifacts,
        options.artifactChecksums.checksumJsonPath,
        options.artifactChecksums.checksumTextPath,
        options.releaseManifest.installerManifestPath,
        options.releaseManifest.manifestPath,
        options.releaseManifest.releaseNotesProvenancePath,
        options.installationReadme.path,
        `${bundleDirectoryRelative}/${cli_constants_1.RELEASE_NOTES_FILENAME}`,
    ].filter((artifactPath) => typeof artifactPath === 'string' && artifactPath.length > 0);
    const files = Array.from(new Set(sourceArtifactPaths))
        .map((artifactPath) => {
        const sourcePath = (0, output_lifecycle_checksums_1.resolveArtifactPathInsideVersionDirectory)({
            versionDirectory: options.state.versionDirectory,
            versionDirectoryRelative: options.state.versionDirectoryRelative,
            artifactPath,
            label: 'download bundle source',
        });
        if (!node_fs_1.default.existsSync(sourcePath) || !node_fs_1.default.statSync(sourcePath).isFile()) {
            throw (0, errors_1.createUsageError)('Release download bundle is missing an expected user-facing artifact.', [
                'Reason: download-bundle-source-missing',
                `Artifact: ${artifactPath}`,
                'Recovery: regenerate the release download bundle after build artifacts are finalized.',
                'Exit behavior: exits before user download bundle files are reported.',
            ]);
        }
        return artifactPath;
    })
        .sort();
    return {
        status: 'created',
        directory: bundleDirectoryRelative,
        files,
    };
}
function copyStagedNoticeFilesToDownloadBundle(options) {
    if (options.noticeFiles.length === 0) {
        return [];
    }
    if (options.state.stagingDirectory === null) {
        throw (0, errors_1.createUsageError)('Release download bundle notice copy requires a resolved staging directory.', [
            'Exit behavior: exits before user download bundle files are created.',
        ]);
    }
    const noticeFiles = Array.from(new Set(options.noticeFiles)).sort();
    return noticeFiles.map((noticeFile) => {
        if (node_path_1.default.basename(noticeFile) !== noticeFile) {
            throw (0, errors_1.createUsageError)('Release notice file name is invalid for download bundle copy.', [
                'Reason: invalid-notice-file-name',
                `Notice file: ${noticeFile}`,
                'Recovery: keep notice file names as top-level file names without path separators.',
                'Exit behavior: exits before user download bundle files are created.',
            ]);
        }
        const sourcePath = node_path_1.default.join(options.state.stagingDirectory, noticeFile);
        const destinationPath = node_path_1.default.join(options.bundleDirectory, noticeFile);
        if (!node_fs_1.default.existsSync(sourcePath) || !node_fs_1.default.statSync(sourcePath).isFile()) {
            throw (0, errors_1.createUsageError)('Release download bundle is missing a staged notice file.', [
                'Reason: download-bundle-notice-source-missing',
                `Notice file: ${noticeFile}`,
                'Recovery: regenerate release staging output before assembling download bundle.',
                'Exit behavior: exits before user download bundle files are reported.',
            ]);
        }
        node_fs_1.default.copyFileSync(sourcePath, destinationPath);
        return `${options.bundleDirectoryRelative}/${noticeFile}`;
    });
}
