"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkReleaseState = checkReleaseState;
exports.resolveReleaseOutputOperation = resolveReleaseOutputOperation;
exports.resolveReleaseNotesDraft = resolveReleaseNotesDraft;
exports.resolveReleaseStagingPayload = resolveReleaseStagingPayload;
exports.resolveReleaseArchivePayloads = resolveReleaseArchivePayloads;
exports.resolveReleaseArtifactChecksums = resolveReleaseArtifactChecksums;
exports.resolveReleaseInstallerAssets = resolveReleaseInstallerAssets;
exports.resolveReleaseManifest = resolveReleaseManifest;
exports.resolveReleaseDownloadBundle = resolveReleaseDownloadBundle;
exports.resolveReleaseInstallationReadme = resolveReleaseInstallationReadme;
exports.resolveReleaseNotesSourceSummary = resolveReleaseNotesSourceSummary;
// Responsibility-focused extraction from index-command-orchestration.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 repository_state_1 = require("./repository-state");
const output_lifecycle_1 = require("./output-lifecycle");
const release_notes_1 = require("./release-notes");
const index_command_surface_1 = require("./index-command-surface");
const index_contract_renderer_1 = require("./index-contract-renderer");
function checkReleaseState(releaseSubcommand, outputDir, commandInstance, dirty) {
    if (!(0, index_command_surface_1.releaseSubcommandHasOption)(releaseSubcommand, 'version')) {
        return {
            cleanRequired: false,
            dirtyAllowed: false,
            dirtyPaths: [],
            ignoredGeneratedOutputPaths: [],
        };
    }
    const repositoryRoot = (0, index_contract_renderer_1.getRootCommand)(commandInstance).configRepositoryContext?.root ?? process.cwd();
    if (releaseSubcommand.name === 'check') {
        const state = (0, repository_state_1.checkReleaseRepositoryState)({
            repositoryRoot,
            outputDir,
            allowDirty: true,
        });
        return {
            cleanRequired: false,
            dirtyAllowed: false,
            dirtyPaths: state.ok ? state.dirtyPaths : state.dirtyPaths,
            ignoredGeneratedOutputPaths: state.ok ? state.ignoredGeneratedOutputPaths : state.ignoredGeneratedOutputPaths,
        };
    }
    const state = (0, repository_state_1.checkReleaseRepositoryState)({
        repositoryRoot,
        outputDir,
        allowDirty: dirty,
    });
    if (!state.ok) {
        throw (0, errors_1.createUsageError)(state.message, [
            `Command: release ${releaseSubcommand.name}`,
            `Dirty paths: ${state.dirtyPaths.join(', ')}`,
            `Ignored generated output paths: ${state.ignoredGeneratedOutputPaths.length > 0 ? state.ignoredGeneratedOutputPaths.join(', ') : '(none)'}`,
            `Recovery: ${state.correctiveAction}`,
            'Exit behavior: exits before generated release output directories or artifacts are created.',
        ]);
    }
    return {
        cleanRequired: !dirty,
        dirtyAllowed: dirty,
        dirtyPaths: state.dirtyPaths,
        ignoredGeneratedOutputPaths: state.ignoredGeneratedOutputPaths,
    };
}
function resolveReleaseOutputOperation(options) {
    if (options.releaseSubcommand.name === 'retention') {
        if (options.outputState.versionDirectoryRelative === null || options.version === null) {
            throw (0, errors_1.createUsageError)('Release retention requires an explicit release version.', [
                'Exit behavior: exits before local generated release output is pruned.',
            ]);
        }
        return (0, output_lifecycle_1.applyReleaseRetention)({
            state: options.outputState,
            currentVersion: options.version,
            keepSuccessfulPriorCount: (0, output_lifecycle_1.parseRetentionKeep)(options.keep),
            dryRun: options.dryRun,
        });
    }
    if (options.releaseSubcommand.name === 'cleanup') {
        return (0, output_lifecycle_1.applyReleaseCleanup)({
            state: options.outputState,
            confirm: options.confirm,
            dryRun: options.dryRun,
        });
    }
    if (options.dryRun) {
        return (0, output_lifecycle_1.createDryRunOperation)('dry-run', options.outputState.versionDirectoryRelative === null
            ? `Dry run did not modify local generated release output under ${options.outputState.releaseRootRelative}.`
            : `Dry run did not modify local generated release output under ${options.outputState.versionDirectoryRelative}.`);
    }
    if (options.releaseSubcommand.name === 'build') {
        return (0, output_lifecycle_1.prepareFreshReleaseBuildDirectory)(options.outputState);
    }
    if (options.releaseSubcommand.name === 'notes') {
        return {
            kind: 'release-notes-draft',
            dryRun: false,
            changed: true,
            removedPaths: [],
            retainedPaths: options.outputState.versionDirectoryRelative === null ? [] : [options.outputState.versionDirectoryRelative],
            message: 'Generated editable draft release notes in the versioned release directory.',
        };
    }
    if (options.releaseSubcommand.name === 'installer') {
        return {
            kind: 'installer-assets',
            dryRun: false,
            changed: true,
            removedPaths: [],
            retainedPaths: options.outputState.versionDirectoryRelative === null ? [] : [options.outputState.versionDirectoryRelative],
            message: 'Generated local installer assets in the versioned release directory without website upload.',
        };
    }
    return {
        kind: 'report-only',
        dryRun: false,
        changed: false,
        removedPaths: [],
        retainedPaths: [],
        message: `Release ${options.releaseSubcommand.name} did not modify local generated release output in this checkpoint.`,
    };
}
function resolveReleaseNotesDraft(options) {
    if (!['build', 'notes'].includes(options.releaseSubcommand.name)) {
        return (0, release_notes_1.createNotApplicableReleaseNotesDraft)();
    }
    if (options.dryRun) {
        return (0, release_notes_1.createSkippedReleaseNotesDraft)({
            versionDirectoryRelative: options.outputState.versionDirectoryRelative,
            sourceSummary: options.releaseNotesSourceSummary,
        });
    }
    if (options.version === null ||
        options.outputState.versionDirectory === null ||
        options.outputState.versionDirectoryRelative === null ||
        options.releaseNotesSourceSummary === null) {
        return (0, release_notes_1.createNotApplicableReleaseNotesDraft)();
    }
    return (0, release_notes_1.writeReleaseNotesDraft)({
        repositoryRoot: options.repositoryRoot,
        version: options.version,
        versionDirectory: options.outputState.versionDirectory,
        versionDirectoryRelative: options.outputState.versionDirectoryRelative,
        sourceSummary: options.releaseNotesSourceSummary,
    });
}
function resolveReleaseStagingPayload(options) {
    if (options.releaseSubcommand.name !== 'build') {
        return (0, output_lifecycle_1.createNotApplicableStagingPayload)();
    }
    if (options.dryRun) {
        return (0, output_lifecycle_1.createSkippedStagingPayload)(options.outputState);
    }
    if (options.version === null || !options.operation.changed) {
        return (0, output_lifecycle_1.createNotApplicableStagingPayload)();
    }
    return (0, output_lifecycle_1.populateReleaseStagingPayload)({
        repositoryRoot: options.repositoryRoot,
        state: options.outputState,
        version: options.version,
        installedCommandName: options.installedCommandName,
        releaseNotesSourceSummary: options.releaseNotesSourceSummary,
    });
}
function resolveReleaseArchivePayloads(options) {
    if (options.releaseSubcommand.name !== 'build') {
        return (0, output_lifecycle_1.createNotApplicableArchivePayloads)();
    }
    if (options.dryRun) {
        return (0, output_lifecycle_1.createSkippedArchivePayloads)(options.outputState);
    }
    if (options.version === null || options.stagingPayload.status !== 'created') {
        return (0, output_lifecycle_1.createNotApplicableArchivePayloads)();
    }
    return (0, output_lifecycle_1.populateReleaseArchivePayloads)({
        state: options.outputState,
        stagingPayload: options.stagingPayload,
        packageName: options.packageName,
        version: options.version,
        installedCommandName: options.installedCommandName,
    });
}
function resolveReleaseArtifactChecksums(options) {
    if (options.releaseSubcommand.name !== 'build') {
        return (0, output_lifecycle_1.createNotApplicableArtifactChecksums)();
    }
    if (options.dryRun) {
        return (0, output_lifecycle_1.createSkippedArtifactChecksums)(options.outputState);
    }
    if (options.archivePayloads.status !== 'created' || options.installerAssets.status !== 'created') {
        return (0, output_lifecycle_1.createNotApplicableArtifactChecksums)();
    }
    return (0, output_lifecycle_1.populateReleaseArtifactChecksums)({
        state: options.outputState,
        archivePayloads: options.archivePayloads,
    });
}
function resolveReleaseInstallerAssets(options) {
    if (options.releaseSubcommand.name !== 'build' && options.releaseSubcommand.name !== 'installer') {
        return (0, output_lifecycle_1.createNotApplicableInstallerAssets)();
    }
    if (options.dryRun) {
        return (0, output_lifecycle_1.createSkippedInstallerAssets)(options.outputState);
    }
    if (options.version === null) {
        return (0, output_lifecycle_1.createNotApplicableInstallerAssets)();
    }
    if (options.releaseSubcommand.name === 'build' && options.archivePayloads.status !== 'created') {
        return (0, output_lifecycle_1.createNotApplicableInstallerAssets)();
    }
    return (0, output_lifecycle_1.populateReleaseInstallerAssets)({
        state: options.outputState,
        version: options.version,
        installedCommandName: options.installedCommandName,
    });
}
function resolveReleaseManifest(options) {
    if (options.releaseSubcommand.name !== 'build') {
        return (0, output_lifecycle_1.createNotApplicableReleaseManifest)();
    }
    if (options.dryRun) {
        return (0, output_lifecycle_1.createSkippedReleaseManifest)(options.outputState);
    }
    if (options.version === null ||
        options.artifactChecksums.status !== 'created' ||
        options.releaseNotesSourceSummary === null) {
        return (0, output_lifecycle_1.createNotApplicableReleaseManifest)();
    }
    return (0, output_lifecycle_1.populateReleaseManifest)({
        state: options.outputState,
        version: options.version,
        cliVersion: options.cliVersion,
        installedCommandName: options.commandName,
        stagedCommandPath: options.stagedCommandPath,
        requiredNodeVersion: options.requiredNodeVersion,
        artifactChecksums: options.artifactChecksums,
        releaseNotesSourceSummary: options.releaseNotesSourceSummary,
    });
}
function resolveReleaseDownloadBundle(options) {
    if (options.releaseSubcommand.name !== 'build') {
        return (0, output_lifecycle_1.createNotApplicableDownloadBundle)();
    }
    if (options.dryRun) {
        return (0, output_lifecycle_1.createSkippedDownloadBundle)(options.outputState);
    }
    return (0, output_lifecycle_1.populateReleaseDownloadBundle)({
        state: options.outputState,
        noticeFiles: options.stagingPayload.noticeFiles,
        archivePayloads: options.archivePayloads,
        installerAssets: options.installerAssets,
        artifactChecksums: options.artifactChecksums,
        releaseManifest: options.releaseManifest,
        installationReadme: options.installationReadme,
    });
}
function resolveReleaseInstallationReadme(options) {
    if (options.releaseSubcommand.name !== 'build') {
        return (0, output_lifecycle_1.createNotApplicableInstallationReadme)();
    }
    if (options.dryRun) {
        return (0, output_lifecycle_1.createSkippedInstallationReadme)(options.outputState);
    }
    if (options.version === null) {
        return (0, output_lifecycle_1.createNotApplicableInstallationReadme)();
    }
    return (0, output_lifecycle_1.populateReleaseInstallationReadmeFromBuildMetadata)({
        state: options.outputState,
        version: options.version,
        packageName: options.packageName,
        installedCommandName: options.commandName,
        requiredNodeVersion: options.requiredNodeVersion,
    });
}
function resolveReleaseNotesSourceSummary(options) {
    if (!['build', 'manifest', 'notes'].includes(options.releaseSubcommand.name) || options.version === null) {
        return null;
    }
    return (0, release_notes_1.createReleaseNotesSourceSummary)({
        repositoryRoot: options.repositoryRoot,
        releaseRoot: options.outputState.releaseRoot,
        releaseRootRelative: options.outputState.releaseRootRelative,
        version: options.version,
        notesGenerated: options.outputState.versionDirectory === null
            ? false
            : node_fs_1.default.existsSync(node_path_1.default.join(options.outputState.versionDirectory, cli_constants_1.RELEASE_DOWNLOAD_BUNDLE_DIRECTORY, cli_constants_1.RELEASE_NOTES_FILENAME)) || node_fs_1.default.existsSync(node_path_1.default.join(options.outputState.versionDirectory, cli_constants_1.RELEASE_NOTES_FILENAME)),
    });
}
