"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderReleaseInstallationReadme = renderReleaseInstallationReadme;
exports.requireReadmeArchiveArtifact = requireReadmeArchiveArtifact;
exports.requireReadmeArchiveMetadata = requireReadmeArchiveMetadata;
exports.copyArchiveRootDocumentation = copyArchiveRootDocumentation;
exports.shellWord = shellWord;
exports.shellInstallPathExpression = shellInstallPathExpression;
exports.powershellInstallPathExpression = powershellInstallPathExpression;
// 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 license_guidance_1 = require("../../../lib/license/license-guidance");
const output_lifecycle_installers_1 = require("./output-lifecycle-installers");
const output_lifecycle_output_state_1 = require("./output-lifecycle-output-state");
function renderReleaseInstallationReadme(options) {
    const command = options.metadata.command;
    const posixArchive = requireReadmeArchiveMetadata(options.metadata, 'macos-linux');
    const windowsArchive = requireReadmeArchiveMetadata(options.metadata, 'windows');
    const posixInstallDir = options.metadata.installation.defaultInstallDirectory.posix;
    const posixBinDir = options.metadata.installation.defaultBinDirectory.posix;
    const windowsInstallDir = options.metadata.installation.defaultInstallDirectory.windows;
    const windowsBinDir = options.metadata.installation.defaultBinDirectory.windows;
    const posixInstallDirShell = shellInstallPathExpression(posixInstallDir);
    const posixBinDirShell = shellInstallPathExpression(posixBinDir);
    const windowsInstallDirPowerShell = powershellInstallPathExpression(windowsInstallDir);
    const windowsBinDirPowerShell = powershellInstallPathExpression(windowsBinDir);
    return [
        `# Day Shift ${options.metadata.version} Installation`,
        '',
        `This guide assumes you are reading it from an extracted Day Shift ${options.metadata.version} archive root. It installs the \`${command}\` command using system Node.js ${options.metadata.requiredNodeVersion} and does not require public npm publication.`,
        '',
        '## Extracted Archive',
        '',
        `- POSIX archive for darwin and linux on x64 or arm64: \`${posixArchive.filename}\` (${posixArchive.path})`,
        `- Windows archive for win32 on x64 or arm64: \`${windowsArchive.filename}\` (${windowsArchive.path})`,
        '- Launchers: `bin/`',
        `- Release notes: \`${cli_constants_1.RELEASE_NOTES_FILENAME}\``,
        '',
        '## Prerequisites',
        '',
        `- Install system Node.js ${options.metadata.requiredNodeVersion} before changing an existing installation.`,
        '- Run commands from the extracted archive root.',
        '- Use a user-owned install directory.',
        '',
        'First-run validation from the extracted archive root:',
        '',
        '```sh',
        `./bin/${command} --version`,
        `./bin/${command} about`,
        '```',
        '',
        '## POSIX Shell',
        '',
        `Default install directory: \`${posixInstallDir}\``,
        `Default PATH directory: \`${posixBinDir}\``,
        '',
        '```sh',
        `INSTALL_DIR=${posixInstallDirShell}`,
        `BIN_DIR=${posixBinDirShell}`,
        'STAGE_DIR="$INSTALL_DIR/.install-stage"',
        'mkdir -p "$INSTALL_DIR" "$BIN_DIR"',
        'rm -rf "$STAGE_DIR"',
        'mkdir -p "$STAGE_DIR"',
        'cp -R . "$STAGE_DIR"',
        'rm -rf "$INSTALL_DIR/current"',
        'mv "$STAGE_DIR" "$INSTALL_DIR/current"',
        `ln -sf "$INSTALL_DIR/current/bin/${command}" "$BIN_DIR/${command}"`,
        `"$BIN_DIR/${command}" --version`,
        `"$BIN_DIR/${command}" about`,
        '```',
        '',
        'Direct execution before PATH setup:',
        '',
        '```sh',
        `./bin/${command} --version`,
        `./bin/${command} about`,
        '```',
        '',
        `Add \`${posixBinDir}\` to PATH if \`${command}\` is not found after installation.`,
        '',
        'macOS usually uses `zsh` by default:',
        '',
        '```sh',
        `echo 'export PATH="${posixBinDir}:$PATH"' >> ~/.zshrc`,
        'source ~/.zshrc',
        `command -v ${command}`,
        '```',
        '',
        'If you use `bash` instead:',
        '',
        '```sh',
        `echo 'export PATH="${posixBinDir}:$PATH"' >> ~/.bashrc`,
        'source ~/.bashrc',
        `command -v ${command}`,
        '```',
        '',
        'If the current shell still does not resolve the command, open a new terminal or run it directly from the install path:',
        '',
        '```sh',
        `"${cli_constants_1.DEFAULT_POSIX_INSTALL_DIRECTORY}/current/bin/${command}" --version`,
        `"${cli_constants_1.DEFAULT_POSIX_INSTALL_DIRECTORY}/current/bin/${command}" about`,
        '```',
        '',
        '## Windows PowerShell',
        '',
        `Default install directory: \`${windowsInstallDir}\``,
        `Default PATH directory: \`${windowsBinDir}\``,
        '',
        '```powershell',
        `$InstallDir = ${windowsInstallDirPowerShell}`,
        `$BinDir = ${windowsBinDirPowerShell}`,
        "$StageDir = Join-Path $InstallDir '.install-stage'",
        "$CurrentDir = Join-Path $InstallDir 'current'",
        'New-Item -ItemType Directory -Force -Path $InstallDir, $BinDir | Out-Null',
        'if (Test-Path $StageDir) { Remove-Item -Recurse -Force $StageDir }',
        'New-Item -ItemType Directory -Force -Path $StageDir | Out-Null',
        'Get-ChildItem -Force -Path . | Copy-Item -Destination $StageDir -Recurse -Force',
        'if (Test-Path $CurrentDir) { Remove-Item -Recurse -Force $CurrentDir }',
        'Move-Item -Path $StageDir -Destination $CurrentDir',
        `$Shim = Join-Path $CurrentDir 'bin\\${command}.cmd'`,
        `$Target = Join-Path $BinDir '${command}.cmd'`,
        'Copy-Item -Force -Path $Shim -Destination $Target',
        `& $Target --version`,
        `& $Target about`,
        '```',
        '',
        'Direct execution before PATH setup:',
        '',
        '```powershell',
        `$Direct = Join-Path (Join-Path (Get-Location) 'bin') '${command}.cmd'`,
        '& $Direct --version',
        '& $Direct about',
        '```',
        '',
        `Add \`${windowsBinDir}\` to PATH if \`${command}\` is not found after installation. On Windows, open a new terminal after changing PATH.`,
        '',
        '## Beta and VIP signed license file',
        '',
        ...(0, license_guidance_1.renderBetaVipSignedLicenseGuidanceLines)(command).map((line) => `- ${line}`),
        '',
        '## Upgrade or Reinstall',
        '',
        'Repeat the platform install steps from a newly extracted archive. The manual install flow stages files before switching `current`; if a command fails before the switch, the previous install remains in place.',
        '',
        '## Uninstall',
        '',
        'Remove the install directory and the command shim or symlink from the PATH directory.',
        '',
        '```sh',
        `rm -rf ${posixInstallDirShell} ${shellInstallPathExpression(`${posixBinDir}/${command}`)}`,
        '```',
        '',
        '```powershell',
        `Remove-Item -Recurse -Force ${windowsInstallDirPowerShell}`,
        `Remove-Item -Force ${powershellInstallPathExpression(`${windowsBinDir}\\${command}.cmd`)}`,
        '```',
        '',
        '## Troubleshooting',
        '',
        `- Node.js prerequisite: run \`node --version\` and install Node.js ${options.metadata.requiredNodeVersion} if \`${command}\` does not start.`,
        `- PATH setup: if \`${command}\` is not found, run it directly from \`./bin\` or from the install path, add the PATH directory shown above, and reload your shell profile or open a new terminal.`,
        '- Archive choice: use the darwin/linux archive for POSIX shell systems and the win32 archive for Windows PowerShell.',
        '- Replacement failure: retry after fixing permissions or locks; the staged install directory can be removed safely before retrying.',
        '',
        '## Support handoff',
        '',
        `When requesting support, include the release version \`${options.metadata.version}\`, the platform archive filename, the output from \`./bin/${command} --version\`, the output from \`./bin/${command} about\`, and any install error text.`,
        '',
    ].join('\n');
}
function requireReadmeArchiveArtifact(manifest, target) {
    const artifact = manifest.artifacts.find((candidate) => candidate.kind === 'archive' && candidate.target === target && candidate.runtimeModel === 'system-node');
    if (artifact === undefined) {
        throw (0, errors_1.createUsageError)('Release installation README requires archive metadata for every supported platform.', [
            'Reason: installation-readme-missing-archive',
            `Target: ${target}`,
            'Recovery: regenerate release archives, checksums, and manifest metadata before README generation.',
            'Exit behavior: exits before successful-release state is recorded.',
        ]);
    }
    return artifact;
}
function requireReadmeArchiveMetadata(metadata, target) {
    const artifact = metadata.archives.find((candidate) => candidate.target === target);
    if (artifact === undefined) {
        throw (0, errors_1.createUsageError)('Release installation README requires archive metadata for every supported platform.', [
            'Reason: installation-readme-missing-archive',
            `Target: ${target}`,
            'Recovery: regenerate release archives and README metadata.',
            'Exit behavior: exits before successful-release state is recorded.',
        ]);
    }
    return artifact;
}
function copyArchiveRootDocumentation(options) {
    const bundleDirectory = node_path_1.default.join(options.versionDirectory, output_lifecycle_output_state_1.RELEASE_DOWNLOAD_BUNDLE_DIRECTORY);
    for (const filename of [output_lifecycle_output_state_1.RELEASE_INSTALLATION_README_FILENAME, cli_constants_1.RELEASE_NOTES_FILENAME]) {
        const sourcePath = node_path_1.default.join(bundleDirectory, filename);
        if (!node_fs_1.default.existsSync(sourcePath) || !node_fs_1.default.statSync(sourcePath).isFile()) {
            throw (0, errors_1.createUsageError)('Release archive payload requires generated download bundle documentation.', [
                'Reason: archive-root-documentation-missing',
                `Missing file: ${filename}`,
                'Recovery: regenerate release notes and installation guidance before archive creation.',
                'Exit behavior: exits before successful-release state is recorded.',
            ]);
        }
        node_fs_1.default.copyFileSync(sourcePath, node_path_1.default.join(options.targetDirectory, filename));
    }
}
function shellWord(value) {
    return (0, output_lifecycle_installers_1.shellQuote)(value);
}
function shellInstallPathExpression(value) {
    if (value === '$HOME') {
        return '"$HOME"';
    }
    if (value.startsWith('$HOME/')) {
        return `"$HOME/${value.slice('$HOME/'.length)}"`;
    }
    return shellWord(value);
}
function powershellInstallPathExpression(value) {
    if (value === '$HOME') {
        return '$HOME';
    }
    if (value.startsWith('$HOME\\')) {
        return `(Join-Path $HOME ${(0, output_lifecycle_installers_1.powershellQuote)(value.slice('$HOME\\'.length))})`;
    }
    return (0, output_lifecycle_installers_1.powershellQuote)(value);
}
