"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateReleaseInstallationReadme = validateReleaseInstallationReadme;
exports.createReleaseInstallationReadmeMetadataFromManifest = createReleaseInstallationReadmeMetadataFromManifest;
exports.createReleaseInstallationReadmeMetadataFromBuildMetadata = createReleaseInstallationReadmeMetadataFromBuildMetadata;
// Responsibility-focused extraction from output-lifecycle-installation-readme.ts.
const errors_1 = require("../../../lib/errors");
const output_lifecycle_manifest_1 = require("./output-lifecycle-manifest");
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");
function validateReleaseInstallationReadme(options) {
    const metadata = options.metadata ??
        (options.manifest === undefined ? null : createReleaseInstallationReadmeMetadataFromManifest(options.manifest));
    if (metadata === null) {
        throw (0, errors_1.createUsageError)('Release installation README validation requires release metadata.', [
            'Reason: installation-readme-metadata-missing',
            'Recovery: regenerate README guidance from release metadata.',
            'Exit behavior: exits before successful-release state is recorded.',
        ]);
    }
    const requiredText = [
        `# Day Shift ${metadata.version} Installation`,
        metadata.version,
        metadata.command,
        metadata.requiredNodeVersion,
        metadata.installation.defaultInstallDirectory.posix,
        metadata.installation.defaultInstallDirectory.windows,
        metadata.installation.defaultBinDirectory.posix,
        metadata.installation.defaultBinDirectory.windows,
        `./bin/${metadata.command} --version`,
        `./bin/${metadata.command} about`,
        `${metadata.command} --version`,
        `${metadata.command} about`,
        'Extracted Archive',
        'POSIX Shell',
        'Windows PowerShell',
        'Beta and VIP signed license file',
        'signed offline Day Shift license file',
        'trusted Day Shift website/server-side path',
        `${metadata.command} license install <license-file>`,
        `${metadata.command} license status --format json`,
        'Troubleshooting',
        'Support handoff',
        'Upgrade or Reinstall',
        'Uninstall',
    ];
    for (const artifact of metadata.archives) {
        requiredText.push(artifact.filename, artifact.path);
        for (const supportedOs of artifact.supportedOs) {
            requiredText.push(supportedOs);
        }
    }
    const missing = requiredText.filter((token) => !options.markdown.includes(token));
    if (missing.length > 0) {
        throw (0, errors_1.createUsageError)('Release installation README is missing manifest-backed guidance.', [
            'Reason: installation-readme-metadata-drift',
            `Missing content: ${missing.join(', ')}`,
            'Recovery: regenerate README guidance from the release manifest and checksum metadata.',
            'Exit behavior: exits before successful-release state is recorded.',
        ]);
    }
    const forbiddenPatterns = [
        { label: 'source checkout path', pattern: /\bsrc\/|\bdist\/cli\/index\.js\b|\.\/dist\b/ },
        { label: 'public npm install', pattern: /\bnpm\s+install\b|\bnpx\b|\bpnpm\s+dlx\b/ },
        { label: 'project repository write', pattern: /project repository|inside your repository|repo checkout/i },
        { label: 'literal HOME path example', pattern: /'\$HOME[\\/]/ },
        { label: 'public issuer command', pattern: /\bday-shift\s+license\s+issue\b/i },
        { label: 'private issuer script', pattern: /\bissue-local-license\.js\b/i },
        { label: 'private issuer helper', pattern: /\blicense-issuer\b/i },
        { label: 'private operator directory', pattern: /\blocal-license-ops\b/i },
        { label: 'private recipient input', pattern: /\brecipients\.(?:csv|json)\b/i },
        {
            label: 'private generated license batch',
            pattern: /\blicenses-out\b|\b(?:beta|vip)[\w.-]*licenses?[\w.-]*\.(?:json|zip|tgz|tar\.gz)\b/i,
        },
        { label: 'private issuance report', pattern: /\bissuance-report\.json\b/i },
        {
            label: 'private signing key',
            pattern: /\bprivate signing key\b|\blicense signing key\b|\bsigning-key\.(?:pem|key|json)\b/i,
        },
        {
            label: 'private support record',
            pattern: /\bsupport-records?\b|\bsupport-archive\.(?:zip|tgz|tar\.gz|enc|json)\b/i,
        },
        {
            label: 'email license delivery promise',
            pattern: /\bemail(?:ed)?\s+(?:JSON|license file|delivery|attachment)s?\b|\bsend\b[\s\S]{0,80}\blicense\b[\s\S]{0,80}\bemail\b/i,
        },
        { label: 'short-code redemption promise', pattern: /\bredeem(?: a)? short[- ]code\b|\bshort pasteable code\b/i },
        { label: 'online activation promise', pattern: /\bonline activation required\b|\bactivate online\b/i },
        { label: 'SSO activation promise', pattern: /\bSSO required\b|\blog in with SSO\b/i },
    ];
    const forbidden = forbiddenPatterns.filter((entry) => entry.pattern.test(options.markdown));
    if (forbidden.length > 0) {
        throw (0, errors_1.createUsageError)('Release installation README contains unsupported installation guidance.', [
            'Reason: installation-readme-forbidden-guidance',
            `Forbidden guidance: ${forbidden.map((entry) => entry.label).join(', ')}`,
            'Recovery: keep README examples focused on downloaded release artifacts and user-owned install locations.',
            'Exit behavior: exits before successful-release state is recorded.',
        ]);
    }
}
function createReleaseInstallationReadmeMetadataFromManifest(manifest) {
    const normalizedManifest = (0, output_lifecycle_manifest_1.normalizeReleaseManifestData)(manifest);
    return {
        version: normalizedManifest.version,
        command: normalizedManifest.command.installedName,
        requiredNodeVersion: normalizedManifest.runtime.requiredNodeVersion,
        installation: normalizedManifest.installation,
        archives: [
            (0, output_lifecycle_installation_readme_rendering_1.requireReadmeArchiveArtifact)(normalizedManifest, 'macos-linux'),
            (0, output_lifecycle_installation_readme_rendering_1.requireReadmeArchiveArtifact)(normalizedManifest, 'windows'),
        ].map((artifact) => ({
            target: artifact.target,
            filename: artifact.filename,
            path: artifact.path,
            supportedOs: artifact.supportedOs,
        })),
    };
}
function createReleaseInstallationReadmeMetadataFromBuildMetadata(options) {
    if (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 packageSlug = (0, output_lifecycle_staging_1.normalizeArchiveNamePart)(options.packageName ?? 'day-shift');
    const posixArchiveFilename = `${packageSlug}-${options.version}-macos-linux-system-node.tar.gz`;
    const windowsArchiveFilename = `${packageSlug}-${options.version}-windows-system-node.zip`;
    return {
        version: options.version,
        command: options.installedCommandName,
        requiredNodeVersion: (0, output_lifecycle_manifest_1.requireManifestString)(options.requiredNodeVersion, 'Node.js requirement', 'missing-node-version-requirement'),
        installation: {
            readmePath: `${(0, output_lifecycle_staging_1.resolveRequiredDownloadBundleRelativeDirectory)(options.state)}/${output_lifecycle_output_state_1.RELEASE_INSTALLATION_README_FILENAME}`,
            defaultInstallDirectory: {
                posix: output_lifecycle_output_state_1.DEFAULT_POSIX_INSTALL_DIRECTORY,
                windows: output_lifecycle_output_state_1.DEFAULT_WINDOWS_INSTALL_DIRECTORY,
            },
            defaultBinDirectory: {
                posix: output_lifecycle_output_state_1.DEFAULT_POSIX_BIN_DIRECTORY,
                windows: output_lifecycle_output_state_1.DEFAULT_WINDOWS_BIN_DIRECTORY,
            },
        },
        archives: [
            {
                target: 'macos-linux',
                filename: posixArchiveFilename,
                path: `${(0, output_lifecycle_staging_1.resolveRequiredDownloadBundleRelativeDirectory)(options.state)}/${posixArchiveFilename}`,
                supportedOs: ['darwin', 'linux'],
            },
            {
                target: 'windows',
                filename: windowsArchiveFilename,
                path: `${(0, output_lifecycle_staging_1.resolveRequiredDownloadBundleRelativeDirectory)(options.state)}/${windowsArchiveFilename}`,
                supportedOs: ['win32'],
            },
        ],
    };
}
