import { existsSync } from "node:fs";
import path from "node:path";

export function resolvePython(rootDir) {
  if (process.env.HERMES_PYTHON) {
    return path.isAbsolute(process.env.HERMES_PYTHON)
      ? process.env.HERMES_PYTHON
      : path.join(rootDir, process.env.HERMES_PYTHON);
  }

  const venvPython = path.join(rootDir, ".venv", "bin", "python");
  if (existsSync(venvPython)) return venvPython;
  return "python3";
}

export function resolveMapsPython(rootDir) {
  return resolveNamedPython(rootDir, "HERMES_MAPS_PYTHON", ".venv-maps");
}

export function resolveScraplingPython(rootDir) {
  return resolveNamedPython(rootDir, "HERMES_SCRAPLING_PYTHON", ".venv-scrapling");
}

export function resolveOsintPython(rootDir) {
  return resolveNamedPython(rootDir, "HERMES_OSINT_PYTHON", ".venv-osint");
}

function resolveNamedPython(rootDir, envName, venvName) {
  const configured = process.env[envName];
  if (configured) {
    return path.isAbsolute(configured) ? configured : path.join(rootDir, configured);
  }

  const venvPython = path.join(rootDir, venvName, "bin", "python");
  if (existsSync(venvPython)) return venvPython;
  return resolvePython(rootDir);
}
