import { readConfigFile } from "./config-file.js";
import { existsSync, realpathSync } from "node:fs";
import { resolve } from "node:path";
import { config as loadDotenv } from "dotenv";
import { resolvezmeelEnvPath } from "./paths.js";
import { maybeRepairLegacyWorktreeConfigAndEnvFiles } from "./worktree-config.js";
import { AUTH_BASE_URL_MODES, DEPLOYMENT_EXPOSURES, DEPLOYMENT_MODES, SECRET_PROVIDERS, STORAGE_PROVIDERS, } from "@zmeel/shared";
import { resolveDefaultBackupDir, resolveDefaultEmbeddedPostgresDir, resolveDefaultSecretsKeyFilePath, resolveDefaultStorageDir, resolveHomeAwarePath, } from "./home-paths.js";
const ZMEEL_ENV_FILE_PATH = resolvezmeelEnvPath();
if (existsSync(ZMEEL_ENV_FILE_PATH)) {
    loadDotenv({ path: ZMEEL_ENV_FILE_PATH, override: false, quiet: true });
}
const CWD_ENV_PATH = resolve(process.cwd(), ".env");
const isSameFile = existsSync(CWD_ENV_PATH) && existsSync(ZMEEL_ENV_FILE_PATH)
    ? realpathSync(CWD_ENV_PATH) === realpathSync(ZMEEL_ENV_FILE_PATH)
    : CWD_ENV_PATH === ZMEEL_ENV_FILE_PATH;
if (!isSameFile && existsSync(CWD_ENV_PATH)) {
    loadDotenv({ path: CWD_ENV_PATH, override: false, quiet: true });
}
maybeRepairLegacyWorktreeConfigAndEnvFiles();
export function loadConfig() {
    const saasMode = process.env.ZMEEL_SAAS_MODE === "true";
    const fileConfig = readConfigFile();
    const fileDatabaseMode = (fileConfig?.database.mode === "postgres" ? "postgres" : "embedded-postgres");
    const fileDbUrl = fileDatabaseMode === "postgres"
        ? fileConfig?.database.connectionString
        : undefined;
    const fileDatabaseBackup = fileConfig?.database.backup;
    const fileSecrets = fileConfig?.secrets;
    const fileStorage = fileConfig?.storage;
    const strictModeFromEnv = process.env.ZMEEL_SECRETS_STRICT_MODE;
    const secretsStrictMode = strictModeFromEnv !== undefined
        ? strictModeFromEnv === "true"
        : (fileSecrets?.strictMode ?? false);
    const providerFromEnvRaw = process.env.ZMEEL_SECRETS_PROVIDER;
    const providerFromEnv = providerFromEnvRaw && SECRET_PROVIDERS.includes(providerFromEnvRaw)
        ? providerFromEnvRaw
        : null;
    const providerFromFile = fileSecrets?.provider;
    const secretsProvider = providerFromEnv ?? providerFromFile ?? "local_encrypted";
    const storageProviderFromEnvRaw = process.env.ZMEEL_STORAGE_PROVIDER;
    const storageProviderFromEnv = storageProviderFromEnvRaw && STORAGE_PROVIDERS.includes(storageProviderFromEnvRaw)
        ? storageProviderFromEnvRaw
        : null;
    const storageProvider = storageProviderFromEnv ?? fileStorage?.provider ?? "local_disk";
    const storageLocalDiskBaseDir = resolveHomeAwarePath(process.env.ZMEEL_STORAGE_LOCAL_DIR ??
        fileStorage?.localDisk?.baseDir ??
        resolveDefaultStorageDir());
    const storageS3Bucket = process.env.ZMEEL_STORAGE_S3_BUCKET ?? fileStorage?.s3?.bucket ?? "zmeel";
    const storageS3Region = process.env.ZMEEL_STORAGE_S3_REGION ?? fileStorage?.s3?.region ?? "us-east-1";
    const storageS3Endpoint = process.env.ZMEEL_STORAGE_S3_ENDPOINT ?? fileStorage?.s3?.endpoint ?? undefined;
    const storageS3Prefix = process.env.ZMEEL_STORAGE_S3_PREFIX ?? fileStorage?.s3?.prefix ?? "";
    const storageS3ForcePathStyle = process.env.ZMEEL_STORAGE_S3_FORCE_PATH_STYLE !== undefined
        ? process.env.ZMEEL_STORAGE_S3_FORCE_PATH_STYLE === "true"
        : (fileStorage?.s3?.forcePathStyle ?? false);
    const feedbackExportBackendUrl = process.env.ZMEEL_FEEDBACK_EXPORT_BACKEND_URL?.trim() ||
        process.env.ZMEEL_TELEMETRY_BACKEND_URL?.trim() ||
        undefined;
    const feedbackExportBackendToken = process.env.ZMEEL_FEEDBACK_EXPORT_BACKEND_TOKEN?.trim() ||
        process.env.ZMEEL_TELEMETRY_BACKEND_TOKEN?.trim() ||
        undefined;
    const deploymentModeFromEnvRaw = process.env.ZMEEL_DEPLOYMENT_MODE;
    const deploymentModeFromEnv = deploymentModeFromEnvRaw && DEPLOYMENT_MODES.includes(deploymentModeFromEnvRaw)
        ? deploymentModeFromEnvRaw
        : null;
    const deploymentMode = deploymentModeFromEnv ?? fileConfig?.server.deploymentMode ?? "local_trusted";
    const deploymentExposureFromEnvRaw = process.env.ZMEEL_DEPLOYMENT_EXPOSURE;
    const deploymentExposureFromEnv = deploymentExposureFromEnvRaw &&
        DEPLOYMENT_EXPOSURES.includes(deploymentExposureFromEnvRaw)
        ? deploymentExposureFromEnvRaw
        : null;
    const deploymentExposure = deploymentMode === "local_trusted"
        ? "private"
        : (deploymentExposureFromEnv ?? fileConfig?.server.exposure ?? "private");
    const authBaseUrlModeFromEnvRaw = process.env.ZMEEL_AUTH_BASE_URL_MODE;
    const authBaseUrlModeFromEnv = authBaseUrlModeFromEnvRaw &&
        AUTH_BASE_URL_MODES.includes(authBaseUrlModeFromEnvRaw)
        ? authBaseUrlModeFromEnvRaw
        : null;
    const publicUrlFromEnv = process.env.ZMEEL_PUBLIC_URL;
    const authPublicBaseUrlRaw = process.env.ZMEEL_AUTH_PUBLIC_BASE_URL ??
        process.env.BETTER_AUTH_URL ??
        process.env.BETTER_AUTH_BASE_URL ??
        publicUrlFromEnv ??
        fileConfig?.auth?.publicBaseUrl;
    const authPublicBaseUrl = authPublicBaseUrlRaw?.trim() || undefined;
    const authBaseUrlMode = authBaseUrlModeFromEnv ??
        fileConfig?.auth?.baseUrlMode ??
        (authPublicBaseUrl ? "explicit" : "auto");
    const disableSignUpFromEnv = process.env.ZMEEL_AUTH_DISABLE_SIGN_UP;
    const authDisableSignUp = disableSignUpFromEnv !== undefined
        ? disableSignUpFromEnv === "true"
        : (fileConfig?.auth?.disableSignUp ?? false);
    const allowedHostnamesFromEnvRaw = process.env.ZMEEL_ALLOWED_HOSTNAMES;
    const allowedHostnamesFromEnv = allowedHostnamesFromEnvRaw
        ? allowedHostnamesFromEnvRaw
            .split(",")
            .map((value) => value.trim().toLowerCase())
            .filter((value) => value.length > 0)
        : null;
    const publicUrlHostname = authPublicBaseUrl
        ? (() => {
            try {
                return new URL(authPublicBaseUrl).hostname.trim().toLowerCase();
            }
            catch {
                return null;
            }
        })()
        : null;
    const allowedHostnames = Array.from(new Set([
        ...(allowedHostnamesFromEnv ?? fileConfig?.server.allowedHostnames ?? []),
        ...(publicUrlHostname ? [publicUrlHostname] : []),
    ]
        .map((value) => value.trim().toLowerCase())
        .filter(Boolean)));
    const companyDeletionEnvRaw = process.env.ZMEEL_ENABLE_COMPANY_DELETION;
    const companyDeletionEnabled = companyDeletionEnvRaw !== undefined
        ? companyDeletionEnvRaw === "true"
        : deploymentMode === "local_trusted";
    const databaseBackupEnabled = process.env.ZMEEL_DB_BACKUP_ENABLED !== undefined
        ? process.env.ZMEEL_DB_BACKUP_ENABLED === "true"
        : (fileDatabaseBackup?.enabled ?? true);
    const databaseBackupIntervalMinutes = Math.max(1, Number(process.env.ZMEEL_DB_BACKUP_INTERVAL_MINUTES) ||
        fileDatabaseBackup?.intervalMinutes ||
        60);
    const databaseBackupRetentionDays = Math.max(1, Number(process.env.ZMEEL_DB_BACKUP_RETENTION_DAYS) ||
        fileDatabaseBackup?.retentionDays ||
        30);
    const databaseBackupDir = resolveHomeAwarePath(process.env.ZMEEL_DB_BACKUP_DIR ??
        fileDatabaseBackup?.dir ??
        resolveDefaultBackupDir());
    const finalDeploymentMode = saasMode ? "authenticated" : deploymentMode;
    const finalDeploymentExposure = saasMode ? "public" : deploymentExposure;
    return {
        deploymentMode: finalDeploymentMode,
        deploymentExposure: finalDeploymentExposure,
        host: process.env.HOST ?? fileConfig?.server.host ?? "127.0.0.1",
        port: Number(process.env.PORT) || fileConfig?.server.port || 3100,
        allowedHostnames,
        authBaseUrlMode,
        authPublicBaseUrl,
        authDisableSignUp,
        databaseMode: fileDatabaseMode,
        databaseUrl: process.env.DATABASE_URL ?? fileDbUrl,
        embeddedPostgresDataDir: resolveHomeAwarePath(fileConfig?.database.embeddedPostgresDataDir ?? resolveDefaultEmbeddedPostgresDir()),
        embeddedPostgresPort: fileConfig?.database.embeddedPostgresPort ?? 54329,
        databaseBackupEnabled,
        databaseBackupIntervalMinutes,
        databaseBackupRetentionDays,
        databaseBackupDir,
        serveUi: process.env.SERVE_UI !== undefined
            ? process.env.SERVE_UI === "true"
            : fileConfig?.server.serveUi ?? true,
        uiDevMiddleware: process.env.ZMEEL_UI_DEV_MIDDLEWARE === "true",
        secretsProvider,
        secretsStrictMode,
        secretsMasterKeyFilePath: resolveHomeAwarePath(process.env.ZMEEL_SECRETS_MASTER_KEY_FILE ??
            fileSecrets?.localEncrypted.keyFilePath ??
            resolveDefaultSecretsKeyFilePath()),
        storageProvider,
        storageLocalDiskBaseDir,
        storageS3Bucket,
        storageS3Region,
        storageS3Endpoint,
        storageS3Prefix,
        storageS3ForcePathStyle,
        feedbackExportBackendUrl,
        feedbackExportBackendToken,
        heartbeatSchedulerEnabled: process.env.HEARTBEAT_SCHEDULER_ENABLED !== "false",
        heartbeatSchedulerIntervalMs: Math.max(10000, Number(process.env.HEARTBEAT_SCHEDULER_INTERVAL_MS) || 30000),
        companyDeletionEnabled,
        telemetryEnabled: fileConfig?.telemetry?.enabled ?? true,
        saasMode,
    };
}
//# sourceMappingURL=config.js.map