import path from 'node:path';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';

const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const resolveFromRoot = (value, fallback) => path.resolve(projectRoot, value || fallback);
const maxUploadBytes = Number.parseInt(process.env.MAX_UPLOAD_MB || '50', 10) * 1024 * 1024;

export const config = Object.freeze({
  projectRoot,
  host: process.env.HOST || '127.0.0.1',
  port: Number.parseInt(process.env.PORT || '47145', 10),
  dataDir: resolveFromRoot(process.env.DATA_DIR, 'data'),
  storageDir: resolveFromRoot(process.env.STORAGE_DIR, 'storage'),
  maxUploadBytes,
  maxJsonBodyBytes: Math.ceil(maxUploadBytes * 4 / 3) + 1024 * 1024,
  defaultRouteRadiusKm: Number.parseFloat(process.env.DEFAULT_ROUTE_RADIUS_KM || '25'),
  defaultPoiTriggerMeters: Number.parseFloat(process.env.DEFAULT_POI_TRIGGER_METERS || '80')
});

export function ensureRuntimeDirectories() {
  for (const directory of [
    config.dataDir,
    path.join(config.storageDir, 'active', 'routes'),
    path.join(config.storageDir, 'trash', 'routes'),
    path.join(config.storageDir, 'uploads')
  ]) {
    fs.mkdirSync(directory, { recursive: true });
  }
}
