import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, isAbsolute, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const appRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const configured = String(process.env.VENDOO_CONFIG_PATH || '').trim();
export const CONFIG_PATH = resolve(isAbsolute(configured) ? configured : join(appRoot, configured || '.env'));

export function readRuntimeConfig() {
  return existsSync(CONFIG_PATH) ? readFileSync(CONFIG_PATH, 'utf8') : '';
}

export function setConfigValue(content, key, value) {
  if (value === undefined || value === null) return content;
  const clean = String(value);
  if (/\r|\n/.test(clean)) throw new Error(`Mehrzeilige Konfigurationswerte sind für ${key} nicht erlaubt.`);
  const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const regex = new RegExp(`^${escaped}=.*$`, 'm');
  const line = `${key}=${clean}`;
  if (regex.test(content)) return content.replace(regex, line);
  return `${content.trimEnd()}\n${line}\n`;
}

export function writeRuntimeConfig(content) {
  mkdirSync(dirname(CONFIG_PATH), { recursive: true });
  writeFileSync(CONFIG_PATH, content, { encoding: 'utf8', mode: 0o600 });
  try { chmodSync(CONFIG_PATH, 0o600); } catch {}
}

export function updateRuntimeConfig(values) {
  let content = readRuntimeConfig();
  for (const [key, value] of Object.entries(values)) {
    if (value === undefined) continue;
    content = setConfigValue(content, key, value);
    process.env[key] = String(value ?? '');
  }
  writeRuntimeConfig(content);
  return CONFIG_PATH;
}
