const SUPPORTED_CONTENT_TYPES = new Set([
  'audio',
  'image',
  'other',
  'text',
  'video',
]);
const DEFAULT_FIELD_LABELS = new Set([
  '下拉字段',
  '单选字段',
  '多选字段',
  '文件字段',
  '文本字段',
  '新字段',
  '长文本字段',
]);
const GENERATED_FIELD_KEY_PATTERN =
  /^(?:field_[A-Za-z0-9]+|(?:text|textarea|radio|checkbox|select|file)_field(?:_\d+)?)$/;

function configuredParameterName(name: unknown) {
  const normalizedName = String(name || '').trim();
  const nameParts = normalizedName.split('.').filter(Boolean);
  return nameParts[nameParts.length - 1] || normalizedName;
}

function isSystemParameter(parameter: any, name: string) {
  return parameter?.systemReserved === true || name === 'user_input';
}

function withConfiguredParameterName(label: unknown, name: unknown) {
  const normalizedLabel = String(label || '').trim();
  const parameterName = configuredParameterName(name);
  if (!parameterName) {
    return normalizedLabel;
  }
  const parts = normalizedLabel.split('>').map((part) => part.trim());
  return parts.length > 1
    ? `${parts.slice(0, -1).join(' > ')} > ${parameterName}`
    : parameterName;
}

function replaceDefaultParameterLabel(label: unknown, name: unknown) {
  const normalizedLabel = String(label || '').trim();
  const normalizedName = String(name || '').trim();
  if (!normalizedLabel || !normalizedName) {
    return normalizedLabel;
  }
  const parts = normalizedLabel.split('>').map((part) => part.trim());
  const lastPart = parts[parts.length - 1] || '';
  if (!DEFAULT_FIELD_LABELS.has(lastPart)) {
    return normalizedLabel;
  }
  const parameterName = configuredParameterName(normalizedName);
  return parts.length > 1
    ? `${parts.slice(0, -1).join(' > ')} > ${parameterName}`
    : parameterName;
}

/**
 * 解析工作流参数在表单中的展示名称。
 *
 * @param parameter 工作流运行参数
 * @returns 用户可见的参数名称
 */
export function resolveWorkflowParameterLabel(parameter: any) {
  const name = String(parameter?.name || '').trim();
  if (!isSystemParameter(parameter, name) && name) {
    return configuredParameterName(name);
  }
  const formLabel = replaceDefaultParameterLabel(parameter?.formLabel, name);
  const displayName = replaceDefaultParameterLabel(
    parameter?.displayName,
    name,
  );
  return formLabel || displayName || name || '参数';
}

/**
 * 解析工作流参数在引用内容中的展示名称。
 *
 * @param parameter 工作流运行参数
 * @returns 用户可见的引用参数名称
 */
export function resolveWorkflowParameterDisplayName(parameter: any) {
  const name = String(parameter?.name || '').trim();
  if (!isSystemParameter(parameter, name) && name) {
    return withConfiguredParameterName(
      parameter?.displayName || parameter?.formLabel,
      name,
    );
  }
  const displayName = replaceDefaultParameterLabel(
    parameter?.displayName,
    name,
  );
  return displayName || resolveWorkflowParameterLabel(parameter);
}

function resolveFieldLabel(field: any) {
  const key = String(field?.key || '').trim();
  const label = String(field?.label || '').trim();
  if (
    key &&
    DEFAULT_FIELD_LABELS.has(label) &&
    !GENERATED_FIELD_KEY_PATTERN.test(key)
  ) {
    return key;
  }
  return label || key;
}

function resolveContentType(
  type: string,
  rawContentType: string,
  parameterContentType: string,
) {
  if (type === 'file') {
    return 'file';
  }
  if (parameterContentType === 'image') {
    return 'image';
  }
  return SUPPORTED_CONTENT_TYPES.has(rawContentType) ? rawContentType : 'text';
}

function resolveDataType(type: string, contentType: string) {
  if (type === 'checkbox') {
    return 'Array';
  }
  if (contentType === 'file') {
    return 'File';
  }
  if (contentType === 'image') {
    return 'Object';
  }
  return 'String';
}

export function resolveWorkflowFormParameters(workflowParams: any) {
  const schema = Array.isArray(workflowParams?.startFormSchema)
    ? workflowParams.startFormSchema
    : [];
  if (schema.length === 0) {
    return workflowParams?.parameters || [];
  }
  const parameterMap = new Map(
    (Array.isArray(workflowParams?.parameters)
      ? workflowParams.parameters
      : []
    ).map((parameter: any) => [
      String(parameter?.name || '').trim(),
      parameter,
    ]),
  );
  return schema.map((field: any) => {
    const type = String(field.type || '').trim() || 'text';
    const rawContentType = String(field.contentType || '').trim();
    const parameter = parameterMap.get(String(field.key || '').trim()) as
      | any
      | undefined;
    const parameterContentType = String(parameter?.contentType || '').trim();
    const contentType = resolveContentType(
      type,
      rawContentType,
      parameterContentType,
    );
    return {
      name: field.key,
      formLabel: resolveFieldLabel(field),
      formDescription: field.description || '',
      formPlaceholder: field.placeholder || '',
      required: Boolean(field.required),
      defaultValue: field.defaultValue,
      enums: Array.isArray(field.options) ? field.options : [],
      contentType,
      formType: type === 'text' || contentType === 'file' ? 'input' : type,
      dataType: resolveDataType(type, contentType),
    };
  });
}
