import fs from 'fs';
import path from 'path';
import { execFileSync } from 'child_process';

function parseDotenv(contents: string) {
  contents
    .split('\n')
    .map((line) => line.trim())
    .filter((line) => line && !line.startsWith('#'))
    .forEach((line) => {
      const idx = line.indexOf('=');
      if (idx === -1) return;
      const key = line.slice(0, idx).trim();
      let value = line.slice(idx + 1).trim();
      if (!key || key in process.env) return;
      if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
        value = value.slice(1, -1);
      }
      process.env[key] = value;
    });
}

export function loadLocalSecrets() {
  const root = process.cwd();
  const plainPath = path.join(root, 'creds', 'secrets.env');
  const encPath = path.join(root, 'creds', 'secrets.enc.env');

  if (fs.existsSync(plainPath)) {
    try {
      parseDotenv(fs.readFileSync(plainPath, 'utf8'));
      return;
    } catch {
      // ignore and try encrypted
    }
  }

  if (fs.existsSync(encPath) && !process.env.SKIP_SOPS_AUTOLOAD) {
    try {
      const output = execFileSync('sops', ['-d', encPath], { encoding: 'utf8' });
      parseDotenv(output);
    } catch {
      // silent fail if sops/key not available
    }
  }
}
