// src/scripts/workflow.ts
import {
  log as logger,
  proxyActivities,
  workflowInfo,
  continueAsNew,
  sleep
} from "@temporalio/workflow";

// src/scripts/serialization.ts
var mooseJsonEncode = (data) => {
  return JSON.stringify(data, (_, value) => {
    if (value instanceof Map) {
      return {
        __type: "Map",
        value: Array.from(value.entries())
      };
    }
    return value;
  });
};

// src/scripts/workflow.ts
var { getDmv2Workflow, getTaskForWorkflow } = proxyActivities({
  startToCloseTimeout: "1 minutes",
  retry: {
    maximumAttempts: 1
  }
});
async function ScriptWorkflow(request, inputData) {
  const state = {
    completedSteps: [],
    currentStep: null,
    failedStep: null,
    scriptPath: null,
    inputData: null
  };
  const results = [];
  const workflowName = request.workflow_name;
  let currentData = inputData?.data || inputData || {};
  logger.info(
    `Starting workflow: ${workflowName} (mode: ${request.execution_mode}) with data: ${JSON.stringify(currentData)}`
  );
  try {
    currentData = JSON.parse(mooseJsonEncode(currentData));
    const workflow = await getDmv2Workflow(workflowName);
    const task = request.execution_mode === "start" ? workflow.config.startingTask : await getTaskForWorkflow(workflowName, request.continue_from_task);
    const result = await handleDmv2Task(workflow, task, currentData);
    results.push(...result);
    return results;
  } catch (error) {
    state.failedStep = workflowName;
    throw error;
  }
}
async function handleDmv2Task(workflow, task, inputData) {
  const configTimeout = task.config.timeout;
  let taskTimeout;
  if (!configTimeout) {
    taskTimeout = "1h";
  } else if (configTimeout === "never") {
    taskTimeout = void 0;
  } else {
    taskTimeout = configTimeout;
  }
  const taskRetries = task.config.retries ?? 3;
  const timeoutMessage = taskTimeout ? `with timeout ${taskTimeout}` : "with no timeout (unlimited)";
  logger.info(
    `Handling task ${task.name} ${timeoutMessage} and retries ${taskRetries}`
  );
  const activityOptions = {
    heartbeatTimeout: "10s",
    retry: {
      maximumAttempts: taskRetries
    }
  };
  if (taskTimeout) {
    activityOptions.startToCloseTimeout = taskTimeout;
  } else {
    activityOptions.scheduleToCloseTimeout = "87600h";
  }
  const { executeDmv2Task } = proxyActivities(activityOptions);
  let taskCompleted = false;
  const monitorTask = async () => {
    logger.info(`Monitor task starting for ${task.name}`);
    while (!taskCompleted) {
      const info = workflowInfo();
      if (info.continueAsNewSuggested) {
        logger.info(`ContinueAsNew suggested by Temporal`);
        return await continueAsNew({
          workflow_name: workflow.name,
          execution_mode: "continue_as_new",
          continue_from_task: task.name
        });
      }
      await sleep(100);
    }
    logger.info(`Monitor task exiting because main task completed`);
  };
  const result = await Promise.race([
    executeDmv2Task(workflow, task, inputData).then((taskResult) => {
      return {
        type: "task_completed",
        data: taskResult
      };
    }).finally(() => {
      taskCompleted = true;
    }),
    monitorTask().then(() => {
      return { type: "continue_as_new", data: void 0 };
    })
  ]);
  if (result.type !== "task_completed") {
    return [];
  }
  const results = [result.data];
  if (!task.config.onComplete?.length) {
    return results;
  }
  for (const childTask of task.config.onComplete) {
    const childResult = await handleDmv2Task(workflow, childTask, result.data);
    results.push(...childResult);
  }
  if (task.name.endsWith("_extract") && result && typeof result === "object" && result.data && typeof result.data === "object" && "hasMore" in result.data && result.data.hasMore === true) {
    logger.info(`Extract task ${task.name} has more data, restarting chain...`);
    const nextBatchResults = await handleDmv2Task(workflow, task, null);
    results.push(...nextBatchResults);
  }
  return results;
}
export {
  ScriptWorkflow
};
//# sourceMappingURL=workflow.mjs.map