import { appConfig } from '../config/index.js';
import { ZintrustLang } from '../lang/lang.js';
export const isNodeRuntime = () => {
    // Avoid importing any `node:*` modules so this file remains Worker-safe.
    // In Workers/Deno, `process` is typically undefined.
    const detectRuntime = appConfig.detectRuntime() !== 'cloudflare';
    return (detectRuntime &&
        typeof process !== ZintrustLang.UNDEFINED &&
        typeof process === ZintrustLang.OBJECT &&
        process !== null &&
        typeof process.versions === ZintrustLang.OBJECT);
};
const getGlobalThis = () => {
    if (typeof globalThis === ZintrustLang.UNDEFINED) {
        return undefined;
    }
    return globalThis;
};
export const getRuntimeMode = () => {
    // 1. Explicit override via env var (if available)
    if (typeof process !== 'undefined' && process.env?.['RUNTIME_MODE'] !== undefined) {
        return process.env['RUNTIME_MODE'];
    }
    // 2. Detect Cloudflare Workers
    // @ts-ignore - navigator is available in workers
    if (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') {
        return 'cloudflare-workers';
    }
    // 3. Detect Container (Docker/Kubernetes)
    // Usually indicated by specific env vars or filesystem characteristics,
    // but simpler to assume Node + invalidating CF check = Node/Container
    if (isNodeRuntime()) {
        // Check for Docker-specific env vars if possible, or default to containers/node-server
        if (typeof process !== 'undefined' &&
            (process.env?.['DOCKER'] !== undefined ||
                process.env?.['KUBERNETES_SERVICE_HOST'] !== undefined)) {
            return 'containers';
        }
        return 'node-server';
    }
    // Default fallback
    return 'node-server';
};
export const detectRuntime = () => {
    const globalRef = getGlobalThis();
    const isNode = isNodeRuntime();
    const isCloudflare = typeof globalRef !== ZintrustLang.UNDEFINED &&
        globalRef !== null &&
        ((globalRef.caches !== undefined &&
            typeof globalRef.caches !== ZintrustLang.UNDEFINED) ||
            typeof globalRef.WebSocketPair === 'function' ||
            typeof globalRef.CF !== ZintrustLang.UNDEFINED);
    const isDeno = typeof globalRef !== ZintrustLang.UNDEFINED &&
        globalRef !== null &&
        typeof globalRef.Deno !== ZintrustLang.UNDEFINED;
    const isBun = typeof globalRef !== ZintrustLang.UNDEFINED &&
        globalRef !== null &&
        typeof globalRef.Bun !== ZintrustLang.UNDEFINED;
    return { isCloudflare, isNode, isDeno, isBun };
};
