import dotenv from 'dotenv';
import { existsSync } from 'node:fs';
import { dirname, isAbsolute, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const appRoot = dirname(fileURLToPath(import.meta.url));
const rootEnvPath = join(appRoot, '.env');

// Lokaler Windows-/Entwicklungsbetrieb: klassische .env zuerst laden.
if (existsSync(rootEnvPath)) dotenv.config({ path: rootEnvPath, override: false });

// Docker/NAS/VPS: schreibbarer persistenter Overlay-Speicher für Eingabemasken.
const configuredPath = String(process.env.VENDOO_CONFIG_PATH || '').trim();
const defaultPath = process.env.VENDOO_DATA_DIR
  ? join(String(process.env.VENDOO_DATA_DIR), 'config', 'vendoo.env')
  : rootEnvPath;
const configCandidate = configuredPath || defaultPath;
const runtimeConfigPath = resolve(isAbsolute(configCandidate) ? configCandidate : join(appRoot, configCandidate));
process.env.VENDOO_CONFIG_PATH = runtimeConfigPath;

if (runtimeConfigPath !== rootEnvPath && existsSync(runtimeConfigPath)) {
  dotenv.config({ path: runtimeConfigPath, override: true });
}

const { hydrateSecretsToEnvironment, migrateRuntimeConfigSecrets } = await import('./lib/secret-store.mjs');
const migration = migrateRuntimeConfigSecrets();
if (migration.migrated.length) console.log(`Security: ${migration.migrated.length} Secrets aus der Runtime-Konfiguration verschlüsselt migriert.`);
hydrateSecretsToEnvironment();

await import('./server.mjs');
