// --- src/core/context.ts ---

import { IWorkflowContext, INodeContext, NodeStatus, IExecutionRecord } from '../types/index.js';
import { v4 as uuidv4 } from 'uuid'; // 需要安装 uuid: npm install uuid @types/uuid

/**
 * 创建一个新的工作流上下文
 * @param definitionId - 工作流定义 ID
 * @param input - 初始输入
 * @param tenantId - 租户 ID (可选)
 * @param userId - 用户 ID (可选)
 * @param userRole - 用户角色 (可选)
 * @returns 初始化后的工作流上下文对象
 */
export function createWorkflowContext(
  definitionId: string,
  input: Record<string, any>,
  tenantId?: string,
  userId?: string,
  userRole?: string
): IWorkflowContext {
  return {
    workflowId: uuidv4(),
    workflowDefinitionId: definitionId,
    input: { ...input }, // 复制输入以避免外部修改
    status: NodeStatus.PENDING,
    variables: {}, // 初始化变量为空对象
    history: [],
    startTime: new Date(),
    tenantId,
    userId,
    userRole,
  };
}

/**
 * 创建一个新的节点上下文
 * @param workflowContext - 关联的工作流上下文
 * @param stepId - 当前步骤 ID
 * @param nodeId - 当前节点 ID (如果适用)
 * @param input - 节点输入
 * @returns 初始化后的节点上下文对象
 */
export function createNodeContext(
  workflowContext: IWorkflowContext,
  stepId: string,
  nodeId: string | undefined,
  input: Record<string, any>
): INodeContext {
  return {
    nodeId: nodeId ?? stepId, // 如果没有 nodeId，使用 stepId
    stepId: stepId,
    input: { ...input }, // 复制输入
    status: NodeStatus.PENDING,
    retries: 0,
    logs: [],
    workflowContext: workflowContext, // 引用工作流上下文
  };
}