import fs from "node:fs";
import path from "node:path";
import os from "node:os";

//#region ../../src/config/paths.ts
/**
* Nix mode detection: When EDWINPAI_NIX_MODE=1 (or legacy EDWIN_NIX_MODE=1),
* the gateway is running under Nix.
* In this mode:
* - No auto-install flows should be attempted
* - Missing dependencies should produce actionable Nix-specific error messages
* - Config is managed externally (read-only from Nix perspective)
*/
function resolveIsNixMode(env = process.env) {
	return env.EDWINPAI_NIX_MODE === "1" || env.EDWIN_NIX_MODE === "1";
}
const isNixMode = resolveIsNixMode();
const LEGACY_STATE_DIRNAMES = [
	".edwin",
	".clawdbot",
	".moltbot",
	".moldbot"
];
const NEW_STATE_DIRNAME = ".edwinpai";
const CONFIG_FILENAME = "edwinpai.json";
const LEGACY_CONFIG_FILENAMES = [
	"edwin.json",
	"clawdbot.json",
	"moltbot.json",
	"moldbot.json"
];
function legacyStateDirs(homedir = os.homedir) {
	return LEGACY_STATE_DIRNAMES.map((dir) => path.join(homedir(), dir));
}
function newStateDir(homedir = os.homedir) {
	return path.join(homedir(), NEW_STATE_DIRNAME);
}
function resolveLegacyStateDirs(homedir = os.homedir) {
	return legacyStateDirs(homedir);
}
function resolveNewStateDir(homedir = os.homedir) {
	return newStateDir(homedir);
}
/**
* State directory for mutable data (sessions, logs, caches).
* Can be overridden via EDWINPAI_STATE_DIR (or legacy EDWIN_STATE_DIR).
* Default: ~/.edwinpai
*/
function resolveStateDir(env = process.env, homedir = os.homedir) {
	const override = (env.EDWINPAI_STATE_DIR ?? env.EDWIN_STATE_DIR)?.trim();
	if (override) return resolveUserPath(override);
	const newDir = newStateDir(homedir);
	const legacyDirs = legacyStateDirs(homedir);
	if (fs.existsSync(newDir)) return newDir;
	const existingLegacy = legacyDirs.find((dir) => {
		try {
			return fs.existsSync(dir);
		} catch {
			return false;
		}
	});
	if (existingLegacy) return existingLegacy;
	return newDir;
}
function resolveUserPath(input) {
	const trimmed = input.trim();
	if (!trimmed) return trimmed;
	if (trimmed.startsWith("~")) {
		const expanded = trimmed.replace(/^~(?=$|[\\/])/, os.homedir());
		return path.resolve(expanded);
	}
	return path.resolve(trimmed);
}
const STATE_DIR = resolveStateDir();
/**
* Config file path (JSON5).
* Can be overridden via EDWINPAI_CONFIG_PATH (or legacy EDWIN_CONFIG_PATH).
* Default: ~/.edwinpai/edwinpai.json
*/
function resolveCanonicalConfigPath(env = process.env, stateDir = resolveStateDir(env, os.homedir)) {
	const override = (env.EDWINPAI_CONFIG_PATH ?? env.EDWIN_CONFIG_PATH)?.trim();
	if (override) return resolveUserPath(override);
	return path.join(stateDir, CONFIG_FILENAME);
}
/**
* Resolve the active config path by preferring existing config candidates
* before falling back to the canonical path.
*/
function resolveConfigPathCandidate(env = process.env, homedir = os.homedir) {
	const existing = resolveDefaultConfigCandidates(env, homedir).find((candidate) => {
		try {
			return fs.existsSync(candidate);
		} catch {
			return false;
		}
	});
	if (existing) return existing;
	return resolveCanonicalConfigPath(env, resolveStateDir(env, homedir));
}
/**
* Active config path (prefers existing config files).
*/
function resolveConfigPath(env = process.env, stateDir = resolveStateDir(env, os.homedir), homedir = os.homedir) {
	const override = (env.EDWINPAI_CONFIG_PATH ?? env.EDWIN_CONFIG_PATH)?.trim();
	if (override) return resolveUserPath(override);
	const stateOverride = (env.EDWINPAI_STATE_DIR ?? env.EDWIN_STATE_DIR)?.trim();
	const existing = [path.join(stateDir, CONFIG_FILENAME), ...LEGACY_CONFIG_FILENAMES.map((name) => path.join(stateDir, name))].find((candidate) => {
		try {
			return fs.existsSync(candidate);
		} catch {
			return false;
		}
	});
	if (existing) return existing;
	if (stateOverride) return path.join(stateDir, CONFIG_FILENAME);
	const defaultStateDir = resolveStateDir(env, homedir);
	if (path.resolve(stateDir) === path.resolve(defaultStateDir)) return resolveConfigPathCandidate(env, homedir);
	return path.join(stateDir, CONFIG_FILENAME);
}
const CONFIG_PATH = resolveConfigPathCandidate();
/**
* Resolve default config path candidates across default locations.
* Order: explicit config path → state-dir-derived paths → new default.
*/
function resolveDefaultConfigCandidates(env = process.env, homedir = os.homedir) {
	const explicit = (env.EDWINPAI_CONFIG_PATH ?? env.EDWIN_CONFIG_PATH)?.trim();
	if (explicit) return [resolveUserPath(explicit)];
	const candidates = [];
	const edwinpaiStateDir = (env.EDWINPAI_STATE_DIR ?? env.EDWIN_STATE_DIR)?.trim();
	if (edwinpaiStateDir) {
		const resolved = resolveUserPath(edwinpaiStateDir);
		candidates.push(path.join(resolved, CONFIG_FILENAME));
		candidates.push(...LEGACY_CONFIG_FILENAMES.map((name) => path.join(resolved, name)));
	}
	const defaultDirs = [newStateDir(homedir), ...legacyStateDirs(homedir)];
	for (const dir of defaultDirs) {
		candidates.push(path.join(dir, CONFIG_FILENAME));
		candidates.push(...LEGACY_CONFIG_FILENAMES.map((name) => path.join(dir, name)));
	}
	return candidates;
}
const DEFAULT_GATEWAY_PORT = 18789;
/**
* Gateway lock directory (ephemeral).
* Default: os.tmpdir()/edwinpai-<uid> (uid suffix when available).
*/
function resolveGatewayLockDir(tmpdir = os.tmpdir) {
	const base = tmpdir();
	const uid = typeof process.getuid === "function" ? process.getuid() : void 0;
	const suffix = uid != null ? `edwinpai-${uid}` : "edwinpai";
	return path.join(base, suffix);
}
const OAUTH_FILENAME = "oauth.json";
/**
* OAuth credentials storage directory.
*
* Precedence:
* - `EDWINPAI_OAUTH_DIR` (or legacy `EDWIN_OAUTH_DIR`)
* - `$*_STATE_DIR/credentials` (canonical server/default)
*/
function resolveOAuthDir(env = process.env, stateDir = resolveStateDir(env, os.homedir)) {
	const override = (env.EDWINPAI_OAUTH_DIR ?? env.EDWIN_OAUTH_DIR)?.trim();
	if (override) return resolveUserPath(override);
	return path.join(stateDir, "credentials");
}
function resolveOAuthPath(env = process.env, stateDir = resolveStateDir(env, os.homedir)) {
	return path.join(resolveOAuthDir(env, stateDir), OAUTH_FILENAME);
}
function resolveGatewayPort(cfg, env = process.env) {
	const envRaw = (env.EDWINPAI_GATEWAY_PORT ?? env.EDWIN_GATEWAY_PORT)?.trim();
	if (envRaw) {
		const parsed = Number.parseInt(envRaw, 10);
		if (Number.isFinite(parsed) && parsed > 0) return parsed;
	}
	const configPort = cfg?.gateway?.port;
	if (typeof configPort === "number" && Number.isFinite(configPort)) {
		if (configPort > 0) return configPort;
	}
	return DEFAULT_GATEWAY_PORT;
}

//#endregion
export { resolveCanonicalConfigPath as a, resolveDefaultConfigCandidates as c, resolveIsNixMode as d, resolveLegacyStateDirs as f, resolveStateDir as g, resolveOAuthPath as h, isNixMode as i, resolveGatewayLockDir as l, resolveOAuthDir as m, DEFAULT_GATEWAY_PORT as n, resolveConfigPath as o, resolveNewStateDir as p, STATE_DIR as r, resolveConfigPathCandidate as s, CONFIG_PATH as t, resolveGatewayPort as u };