/**
 * Backend workflow variable ref → Chinese display label.
 * Mirrors data/agent/workflow_variables.json builtIn entries.
 */
export const BUILTIN_WORKFLOW_VARIABLE_LABELS = {
  'workflow.goal': '工作流目标文本',
  'workflow.boundWorldbook': '绑定世界书摘要',
  'workflow.boundCharacter': '绑定角色卡摘要',
};

/** Build ref → label map from /api/studio/variables response. */
export function buildWorkflowVariableLabelMap(workflowVariables) {
  const map = { ...BUILTIN_WORKFLOW_VARIABLE_LABELS };
  const builtIn = workflowVariables?.builtIn || [];
  const dynamic = workflowVariables?.dynamic || [];
  [...builtIn, ...dynamic].forEach((item) => {
    if (item?.ref && item?.label) {
      map[item.ref] = item.label;
    }
  });
  return map;
}

/**
 * Resolve Chinese label for a workflow variable key shown in run preview.
 * @param {string} ref - e.g. workflow.goal or nodeId.output
 * @param {Record<string, string>} [labelMap] - optional map from buildWorkflowVariableLabelMap
 */
export function getWorkflowVariableLabel(ref, labelMap = BUILTIN_WORKFLOW_VARIABLE_LABELS) {
  if (!ref) return '';
  if (labelMap[ref]) return labelMap[ref];
  const outputMatch = ref.match(/^([^.]+)\.output$/);
  if (outputMatch) {
    return `${outputMatch[1]} · 世界书条目`;
  }
  return ref;
}
