/**
 * 运行时桥接服务配置
 *
 * 集中管理所有环境变量和配置常量
 */
import { homedir } from "node:os";
import path from "node:path";
import fs from "node:fs";
import { fileURLToPath } from "node:url";
/** 服务端口 */
export const port = Number(process.env.AWS_RUNTIME_BRIDGE_PORT || 18081);
/** 默认调度器基础 URL */
export const DEFAULT_SCHEDULER_BASE_URL = "http://localhost:8080";
function normalizeOptionalString(value) {
    if (value == null) {
        return undefined;
    }
    const normalized = String(value).trim();
    return normalized || undefined;
}
function normalizeSchedulerHttpBaseUrl(value) {
    const raw = normalizeOptionalString(value);
    if (!raw) {
        return undefined;
    }
    const repaired = raw.replace(/^((?:https?|wss?):\/\/(?:\[[^\]]+\]|[^/:?#]+):\d+):\d+(?=\/|$)/i, "$1");
    try {
        const url = new URL(repaired);
        if (url.protocol === "ws:") {
            url.protocol = "http:";
        }
        else if (url.protocol === "wss:") {
            url.protocol = "https:";
        }
        else {
            url.protocol = url.protocol.toLowerCase();
        }
        url.hostname = url.hostname.toLowerCase();
        return url.origin;
    }
    catch {
        return repaired.replace(/\/+$/, "");
    }
}
function getAutoRegisterConfigFilePath() {
    const testHomeDir = String(process.env.AWS_TEST_HOME || "").trim();
    return path.join(testHomeDir || homedir(), ".aws-bridge", "config.json");
}
function readAutoRegisterTargetUrls() {
    const configPath = getAutoRegisterConfigFilePath();
    try {
        if (!fs.existsSync(configPath)) {
            return [];
        }
        const parsed = JSON.parse(fs.readFileSync(configPath, "utf-8"));
        const rawTargets = Array.isArray(parsed.autoRegisterTargets)
            ? parsed.autoRegisterTargets
            : [];
        const targetUrls = rawTargets
            .filter((item) => Boolean(item && typeof item === "object" && !Array.isArray(item)))
            .map((target) => normalizeSchedulerHttpBaseUrl(target.serverUrl) ||
            normalizeSchedulerHttpBaseUrl(target.schedulerBaseUrl))
            .filter((url) => Boolean(url));
        if (targetUrls.length > 0) {
            return Array.from(new Set(targetUrls));
        }
        const topLevelUrl = normalizeSchedulerHttpBaseUrl(parsed.serverUrl) ||
            normalizeSchedulerHttpBaseUrl(parsed.schedulerBaseUrl);
        return topLevelUrl ? [topLevelUrl] : [];
    }
    catch {
        return [];
    }
}
/**
 * 解析调度中心基础 URL。
 * 主流程：显式环境变量优先；未配置时，单个自动注册目标可作为宿主机部署的零额外配置回退；多目标不静默取第一个。
 */
export function resolveSchedulerBaseUrl() {
    return resolveSchedulerBaseUrlFrom(undefined);
}
/**
 * 解析调度中心基础 URL。
 * 主流程：服务端请求携带的 scheduler 地址优先；再读显式环境变量；最后回退到单个自动注册目标或默认值。
 */
export function resolveSchedulerBaseUrlFrom(requestSchedulerBaseUrl) {
    const normalizedRequestSchedulerBaseUrl = normalizeSchedulerHttpBaseUrl(requestSchedulerBaseUrl);
    if (normalizedRequestSchedulerBaseUrl) {
        return {
            url: normalizedRequestSchedulerBaseUrl,
            source: "request",
            ambiguousTargetUrls: [],
        };
    }
    const envSchedulerBaseUrl = normalizeSchedulerHttpBaseUrl(process.env.AWS_RUNTIME_SCHEDULER_BASE_URL);
    if (envSchedulerBaseUrl) {
        return {
            url: envSchedulerBaseUrl,
            source: "env",
            ambiguousTargetUrls: [],
        };
    }
    const autoRegisterTargetUrls = readAutoRegisterTargetUrls();
    if (autoRegisterTargetUrls.length === 1) {
        return {
            url: autoRegisterTargetUrls[0] || DEFAULT_SCHEDULER_BASE_URL,
            source: "single-auto-register-target",
            ambiguousTargetUrls: [],
        };
    }
    if (autoRegisterTargetUrls.length > 1) {
        return {
            url: DEFAULT_SCHEDULER_BASE_URL,
            source: "ambiguous-auto-register-targets",
            ambiguousTargetUrls: autoRegisterTargetUrls,
        };
    }
    return {
        url: DEFAULT_SCHEDULER_BASE_URL,
        source: "default",
        ambiguousTargetUrls: [],
    };
}
/** 调度器基础 URL（兼容旧导入；请求处理应优先调用 resolveSchedulerBaseUrl 获取最新值） */
export const schedulerBaseUrl = normalizeSchedulerHttpBaseUrl(process.env.AWS_RUNTIME_SCHEDULER_BASE_URL) ||
    DEFAULT_SCHEDULER_BASE_URL;
/** Node 环境 */
export const nodeEnv = process.env.NODE_ENV || "development";
/** 是否允许浏览宿主机任意目录（默认关闭，仅建议本地排障启用） */
export const allowHostFileBrowser = process.env.AWS_ALLOW_HOST_FILE_BROWSER === "true";
/** CORS 允许来源列表，默认仅允许本机开发前端 */
export const allowedCorsOrigins = String(process.env.AWS_RUNTIME_CORS_ORIGINS ||
    "http://localhost:3000,http://127.0.0.1:3000,http://localhost:5173,http://127.0.0.1:5173")
    .split(",")
    .map((origin) => origin.trim())
    .filter((origin) => origin.length > 0);
/** Runtime bridge no longer supports global callback tokens. */
export function validateProductionToken() { }
/** 获取运行时主目录 */
export function getRuntimeHomeDir() {
    return String(process.env.AWS_RUNTIME_HOME_DIR || "").trim() || homedir();
}
/** 获取 Claude 配置文件路径（AI 配置写入 settings.json） */
export function getClaudeConfigFile(runtimeHome) {
    return (String(process.env.AWS_RUNTIME_CLAUDE_CONFIG_FILE || "").trim() ||
        path.join(runtimeHome, ".claude", "settings.json"));
}
/** 获取 Claude MCP 配置文件路径 */
export function getClaudeMcpConfigFile(runtimeHome) {
    return (String(process.env.AWS_RUNTIME_CLAUDE_MCP_CONFIG_FILE || "").trim() ||
        path.join(runtimeHome, ".claude.json"));
}
/** 获取 Claude Skills 目录 */
export function getClaudeSkillsDir(runtimeHome) {
    return (String(process.env.AWS_RUNTIME_CLAUDE_SKILLS_DIR || "").trim() ||
        path.join(runtimeHome, ".claude", "skills"));
}
/** 获取 OpenCode 配置文件路径 */
export function getOpencodeConfigFile(runtimeHome) {
    return (String(process.env.AWS_RUNTIME_OPENCODE_CONFIG_FILE || "").trim() ||
        path.join(runtimeHome, ".config", "opencode", "opencode.json"));
}
/** 获取内置 ACode 配置文件路径 */
export function getAcodeConfigFile(runtimeHome) {
    return (String(process.env.AWS_RUNTIME_ACODE_CONFIG_FILE || "").trim() ||
        path.join(runtimeHome, ".acode", "config.json"));
}
/** 获取 Codex 配置文件路径 */
export function getCodexConfigFile(runtimeHome) {
    return (String(process.env.AWS_RUNTIME_CODEX_CONFIG_FILE || "").trim() ||
        path.join(runtimeHome, ".codex", "config.toml"));
}
/** 获取 Codex Skills 目录 */
export function getCodexSkillsDir(runtimeHome) {
    return (String(process.env.AWS_RUNTIME_CODEX_SKILLS_DIR || "").trim() ||
        path.join(runtimeHome, ".codex", "skills"));
}
/** 获取 OpenCode Skills 目录 */
export function getOpencodeSkillsDir(runtimeHome) {
    return (String(process.env.AWS_RUNTIME_OPENCODE_SKILLS_DIR || "").trim() ||
        path.join(runtimeHome, ".opencode", "skills"));
}
/** 获取内置 ACode Skills 目录 */
export function getAcodeSkillsDir(runtimeHome) {
    return (String(process.env.AWS_RUNTIME_ACODE_SKILLS_DIR || "").trim() ||
        path.join(runtimeHome, ".acode", "skills"));
}
/**
 * 孤儿进程监控配置
 */
/** 定期扫描间隔（毫秒），默认 30 秒 */
export const ORPHAN_SCAN_INTERVAL = Number(process.env.AWS_ORPHAN_SCAN_INTERVAL || 30000);
/** 自动清理模式: 'auto' | 'alert' | 'manual' */
export const ORPHAN_AUTO_CLEAN_MODE = (process.env.AWS_ORPHAN_AUTO_CLEAN_MODE ||
    "alert");
/** 是否启用定期扫描 */
export const ORPHAN_SCAN_ENABLED = process.env.AWS_ORPHAN_SCAN_ENABLED !== "false";
/** 健康检测：进程最大无响应时间（毫秒），默认 5 分钟 */
export const ORPHAN_UNRESPONSIVE_TIMEOUT = Number(process.env.AWS_ORPHAN_UNRESPONSIVE_TIMEOUT || 300000);
/** 健康检测：CPU 使用率阈值（百分比），超过则认为卡死，默认 100% */
export const ORPHAN_CPU_THRESHOLD = Number(process.env.AWS_ORPHAN_CPU_THRESHOLD || 100);
/** 健康检测：内存使用阈值（MB），超过则认为异常，默认 2GB */
export const ORPHAN_MEMORY_THRESHOLD = Number(process.env.AWS_ORPHAN_MEMORY_THRESHOLD || 2048);
/**
 * 自动注册配置
 */
/** 是否启用自动注册 */
export const AUTO_REGISTER_ENABLED = process.env.AWS_AUTO_REGISTER === "true";
/** 租户 ID */
export const AUTO_REGISTER_TENANT_ID = process.env.AWS_TENANT_ID || "";
/** 用户 API Key */
export const AUTO_REGISTER_USER_KEY = process.env.AWS_USER_KEY || "";
/** 实例名称（默认使用主机名） */
export const AUTO_REGISTER_INSTANCE_NAME = process.env.AWS_INSTANCE_NAME || "";
/** 项目名称 */
export const AUTO_REGISTER_PROJECT_NAME = process.env.AWS_PROJECT_NAME || "";
/** 角色名称 */
export const AUTO_REGISTER_ROLE_NAME = process.env.AWS_ROLE_NAME || "";
/** 工作空间路径 */
export const AUTO_REGISTER_WORKSPACE_PATH = process.env.AWS_WORKSPACE_PATH || "";
/** 注册 IP（优先），兼容 EasyTier 虚拟 IP */
export const AUTO_REGISTER_VIRTUAL_IP = process.env.AWS_REGISTER_IP || process.env.AWS_VIRTUAL_IP || "";
let cachedBridgeVersion;
/**
 * 读取 aws-runtime-bridge package.json 中的版本号。
 * 缓存结果，仅在首次调用时读取文件。
 */
export function getBridgeVersion() {
    if (cachedBridgeVersion !== undefined) {
        return cachedBridgeVersion;
    }
    let version = "unknown";
    try {
        const currentDir = path.dirname(fileURLToPath(import.meta.url));
        const pkgPath = path.resolve(currentDir, "..", "package.json");
        if (fs.existsSync(pkgPath)) {
            const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
            version = pkg.version || "unknown";
        }
    }
    catch {
        // fallback
    }
    cachedBridgeVersion = version;
    return version;
}
