"use strict";

function hasJavaScriptHandler(source) {
  const code = String(source || "");
  return /\bfunction\s+run\s*\(|\b(?:const|let|var)\s+run\s*=|\bmodule\.exports\s*=|\bexports(?:\.run)?\s*=/.test(code);
}

function prepareJavaScriptCommand(source) {
  const code = String(source || "");
  if (hasJavaScriptHandler(code)) return code;
  return `async function run(ctx) {\n${indent(code)}\n}`;
}

function resolveJavaScriptHandler(context) {
  const candidates = [
    context?.run,
    context?.module?.exports,
    context?.module?.exports?.run,
    context?.exports,
    context?.exports?.run
  ];
  return candidates.find((candidate) => typeof candidate === "function") || null;
}

function hasPythonHandler(source) {
  return /^\s*(?:async\s+)?def\s+run\s*\(/m.test(String(source || ""));
}

function preparePythonCommand(source) {
  const code = String(source || "");
  if (hasPythonHandler(code)) return code;
  return `def run(ctx):\n${indent(code || "return None")}`;
}

function indent(value) {
  return String(value || "")
    .split(/\r?\n/)
    .map((line) => `    ${line}`)
    .join("\n");
}

module.exports = {
  hasJavaScriptHandler,
  hasPythonHandler,
  prepareJavaScriptCommand,
  preparePythonCommand,
  resolveJavaScriptHandler
};
