export type CatalogueTreeItem = {
  id: string;
  name: string;
  children?: CatalogueTreeItem[];
};
export const catologueToTree = (
  str: string,
  parentId?: string
): CatalogueTreeItem => {
  const lines = str.split('\n').filter(Boolean);
  const result: CatalogueTreeItem = {
    id: parentId || '1',
    name: '',
    children: []
  };

  const itemMap = new Map<string, CatalogueTreeItem>();
  itemMap.set(result.id, result);

  for (const line of lines) {
    const match = line.match(/\[([\d-]+)\]\s*(.*)/);
    if (!match) continue;

    const [, id, name] = match;
    const parts = id.split('-');
    const parentPath = parts.slice(0, -1).join('-');
    const parent = parentPath ? itemMap.get(parentPath) : result;

    if (!parent) continue;

    const item: CatalogueTreeItem = {
      id,
      name: name.trim(),
      children: []
    };

    itemMap.set(id, item);
    parent.children?.push(item);
  }

  if (!result.name && result.children?.[0]) {
    result.name = result.children[0].name;
    result.children = result.children[0].children;
  }
  
  return result;
}