/**
 * 按内容类型过滤引用选项，并保留当前已选择的旧引用。
 */
export function filterRefOptionsByContentType(
  options: any[],
  acceptedContentTypes: string[],
  currentRef = '',
): any[] {
  if (!acceptedContentTypes.length) {
    return options;
  }
  const accepted = new Set(acceptedContentTypes);
  return options
    .map((option) => {
      const children = Array.isArray(option.children)
        ? filterRefOptionsByContentType(
            option.children,
            acceptedContentTypes,
            currentRef,
          )
        : [];
      const selectable =
        option.selectable === true &&
        (accepted.has(String(option.contentType || '')) ||
          String(option.value || '') === currentRef);
      if (!selectable && children.length === 0) {
        return undefined;
      }
      return {
        ...option,
        selectable,
        children,
      };
    })
    .filter(Boolean);
}

function isAcceptedDataType(dataType: string, acceptedDataTypes: string[]) {
  const normalized = dataType.trim().toLowerCase();
  return acceptedDataTypes.some((acceptedDataType) => {
    const accepted = acceptedDataType.trim().toLowerCase();
    return accepted === 'array'
      ? normalized === 'array' || normalized.startsWith('array<')
      : normalized === accepted;
  });
}

/**
 * 按数据类型过滤引用选项，并保留当前已选择的旧引用。
 */
export function filterRefOptionsByDataType(
  options: any[],
  acceptedDataTypes: string[],
  currentRef = '',
): any[] {
  if (!acceptedDataTypes.length) {
    return options;
  }
  return options
    .map((option) => {
      const children = Array.isArray(option.children)
        ? filterRefOptionsByDataType(
            option.children,
            acceptedDataTypes,
            currentRef,
          )
        : [];
      const selectable =
        option.selectable === true &&
        (isAcceptedDataType(
          String(option.dataType || ''),
          acceptedDataTypes,
        ) ||
          String(option.value || '') === currentRef);
      if (!selectable && children.length === 0) {
        return undefined;
      }
      return {
        ...option,
        selectable,
        children,
      };
    })
    .filter(Boolean);
}
