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

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const SOURCE_ROOT = path.resolve(__dirname, '../..');

function getRootCandidates() {
  return [...new Set([
    process.env.VLCODE_APP_ROOT,
    process.env.VLCODE_UNPACKED_DIR,
    SOURCE_ROOT,
  ].filter(Boolean).map((entry) => path.resolve(entry)))];
}

export function getBundleRoots() {
  return getRootCandidates();
}

export function resolveBundledPath(...segments) {
  const roots = getRootCandidates();
  for (const root of roots) {
    const candidate = path.join(root, ...segments);
    if (fs.existsSync(candidate)) {
      return candidate;
    }
  }
  return path.join(roots[0] || SOURCE_ROOT, ...segments);
}

export function resolvePublicPath(...segments) {
  return resolveBundledPath('public', ...segments);
}

export function resolveSeedWorkflowDir() {
  return resolvePublicPath('seed-workflows');
}

export function resolveDataPath(...segments) {
  return resolveBundledPath('src', 'data', ...segments);
}

export function resolveNodeModulePath(...segments) {
  return resolveBundledPath('node_modules', ...segments);
}
