"use strict";
/**
 * DEF-4: On CLI startup, warn (once per day) if a newer @doquflow/cli is installed
 * in a different npm prefix than the currently-running binary.
 *
 * npm 7+ suppresses postinstall stdout/stderr, so a postinstall-script warning
 * can never reach the user. This module moves the check into the CLI itself so
 * it is seen on first actual use after a mismatched install.
 *
 * The check is:
 *   1. Parse the current binary's prefix from process.argv[1]
 *   2. Scan known alternative prefix paths for a @doquflow/cli with a higher version
 *   3. If found, print a one-line stderr warning with the fix command
 *   4. Cache the result to ~/.docuflow/.prefix-check.json for 24h (avoids slowdown)
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runPrefixCheckIfStale = runPrefixCheckIfStale;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const node_os_1 = __importDefault(require("node:os"));
const prefix_utils_1 = require("./prefix-utils");
const CACHE_FILE = node_path_1.default.join(node_os_1.default.homedir(), ".docuflow", ".prefix-check.json");
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
/** Derive the install prefix from the currently-running CLI entry point. */
function currentCliPrefix() {
    return (0, prefix_utils_1.getMcpEntryPrefix)(process.argv[1] ?? "");
}
/**
 * Run the dual-prefix check if the cache is stale or missing.
 * Never throws — startup must never be blocked.
 *
 * @param currentVersion  The version string from the running CLI's package.json
 */
function runPrefixCheckIfStale(currentVersion) {
    // Skip in non-interactive contexts (CI, pipes) — warning would be noise.
    // DOCUFLOW_CHECK_NOW=1 bypasses this for tests and explicit manual runs.
    if (!process.stdout.isTTY && !process.env.DOCUFLOW_CHECK_NOW)
        return;
    try {
        // Read cache — if fresh and version matches, replay the stored warning (or skip)
        if (node_fs_1.default.existsSync(CACHE_FILE)) {
            const cache = JSON.parse(node_fs_1.default.readFileSync(CACHE_FILE, "utf8"));
            if (cache.currentVersion === currentVersion &&
                Date.now() - cache.checkedAt < CACHE_TTL_MS) {
                if (cache.warn && cache.warnMsg)
                    process.stderr.write(cache.warnMsg + "\n");
                return;
            }
        }
        // Determine which prefix the active binary came from
        const myPrefix = currentCliPrefix() ?? node_path_1.default.dirname(node_path_1.default.dirname(process.execPath));
        // Accept extra prefixes from env var so tests can inject fake installs
        const extras = process.env.DOCUFLOW_EXTRA_PREFIXES
            ? process.env.DOCUFLOW_EXTRA_PREFIXES.split(node_path_1.default.delimiter)
            : [];
        const allInstalls = (0, prefix_utils_1.findInstallsSync)(extras);
        let warnMsg;
        for (const install of allInstalls) {
            if (node_path_1.default.resolve(install.prefix) === node_path_1.default.resolve(myPrefix))
                continue;
            if ((0, prefix_utils_1.semverGt)(install.version, currentVersion)) {
                const shortPrefix = install.prefix.replace(node_os_1.default.homedir(), "~");
                warnMsg =
                    `⚠️  docuflow ${install.version} is installed at ${shortPrefix}` +
                        ` but you are running ${currentVersion}.` +
                        `  Fix: npm install -g @doquflow/cli@latest`;
                break;
            }
        }
        // Persist cache
        try {
            node_fs_1.default.mkdirSync(node_path_1.default.dirname(CACHE_FILE), { recursive: true });
            const cache = {
                checkedAt: Date.now(),
                currentVersion,
                warn: !!warnMsg,
                warnMsg,
            };
            node_fs_1.default.writeFileSync(CACHE_FILE, JSON.stringify(cache), "utf8");
        }
        catch { /* non-fatal */ }
        if (warnMsg)
            process.stderr.write(warnMsg + "\n");
    }
    catch { /* never block startup */ }
}
