"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fingerprintToolchain = fingerprintToolchain;
exports.getToolVersion = getToolVersion;
exports.clearToolchainCache = clearToolchainCache;
const node_child_process_1 = require("node:child_process");
// Cache toolchain result (TTL: 1 minute)
let cachedToolchain = null;
let cacheTimestamp = 0;
const CACHE_TTL_MS = 60 * 1000;
const TOOL_PROBES = [
    { command: "node", args: ["--version"], timeout: 3000 },
    { command: "rustc", args: ["--version"], timeout: 5000 },
    { command: "solana", args: ["--version"], timeout: 5000 },
    { command: "anchor", args: ["--version"], timeout: 5000 },
];
function parseVersion(raw) {
    if (!raw)
        return undefined;
    // Extract first line and trim
    const firstLine = raw.split(/\r?\n/)[0]?.trim();
    if (!firstLine)
        return undefined;
    // Try to extract semantic version pattern (e.g., "v1.2.3" or "1.2.3")
    const match = firstLine.match(/(?:v)?(\d+\.\d+\.\d+(?:[.-].*)?)/);
    if (match) {
        return match[0];
    }
    return firstLine;
}
function probe(command, args, timeout) {
    try {
        let executable = command;
        let spawnArgs = args;
        // Check for stealth mode
        const os = require("node:os");
        const fs = require("node:fs");
        const path = require("node:path");
        if (process.platform === "win32") {
            try {
                const configPath = path.join(os.homedir(), ".uso-config.json");
                if (fs.existsSync(configPath)) {
                    const configJson = JSON.parse(fs.readFileSync(configPath, "utf8"));
                    if (configJson.mode === "wsl") {
                        executable = "wsl.exe";
                        const envSetup = 'source $HOME/.cargo/env 2>/dev/null; export PATH="$HOME/.local/share/solana/install/active_release/bin:$HOME/.avm/bin:$PATH"; export NVM_DIR="$HOME/.nvm"; if [ -s "$NVM_DIR/nvm.sh" ]; then . "$NVM_DIR/nvm.sh" 2>/dev/null; nvm use node 2>/dev/null; fi';
                        spawnArgs = ["-d", "Ubuntu", "-e", "bash", "-c", `${envSetup}; ${command} ${args.join(" ")}`];
                    }
                }
            }
            catch (e) {
                // ignore
            }
        }
        const result = (0, node_child_process_1.spawnSync)(executable, spawnArgs, {
            encoding: "utf8",
            timeout,
            stdio: ["ignore", "pipe", "pipe"],
        });
        if (result.status === 0 && result.stdout) {
            const version = parseVersion(result.stdout);
            return {
                name: command,
                available: true,
                version,
                raw: result.stdout.trim(),
            };
        }
        // Check stderr for version info (some tools output to stderr)
        if (result.stderr && result.stderr.length < 500) {
            const version = parseVersion(result.stderr);
            if (version) {
                return {
                    name: command,
                    available: true,
                    version,
                    raw: result.stderr.trim(),
                };
            }
        }
        return {
            name: command,
            available: false,
            raw: (result.stderr || result.stdout || "").trim(),
        };
    }
    catch (e) {
        const errorMsg = e instanceof Error ? e.message : "Unknown error";
        return {
            name: command,
            available: false,
            raw: errorMsg,
        };
    }
}
function fingerprintToolchain(skipCache = false) {
    // Check cache first
    if (!skipCache) {
        const now = Date.now();
        if (cachedToolchain && now - cacheTimestamp < CACHE_TTL_MS) {
            return cachedToolchain;
        }
    }
    const toolchain = [];
    for (const tool of TOOL_PROBES) {
        const result = probe(tool.command, tool.args, tool.timeout);
        toolchain.push(result);
    }
    // Cache the result
    cachedToolchain = toolchain;
    cacheTimestamp = Date.now();
    return toolchain;
}
function getToolVersion(toolName) {
    const toolchain = fingerprintToolchain();
    return toolchain.find((t) => t.name === toolName);
}
function clearToolchainCache() {
    cachedToolchain = null;
    cacheTimestamp = 0;
}
//# sourceMappingURL=toolchain.js.map