/**
 * Convert raw directory listings — from the native workspace layer
 * (workspace:read-tree) or the server (GET /api/depot/tree) — into the node
 * shape the FileTree component renders:
 * { id, name, type, size, modified, expanded, children, revisionCount? }.
 */

export function formatSize(bytes) {
  if (bytes == null) return '--';
  if (bytes < 1024) return `${bytes} B`;
  const units = ['KB', 'MB', 'GB', 'TB'];
  let value = bytes / 1024;
  let unit = 0;
  while (value >= 1024 && unit < units.length - 1) {
    value /= 1024;
    unit += 1;
  }
  const rounded = value >= 100 ? Math.round(value) : Math.round(value * 10) / 10;
  return `${rounded} ${units[unit]}`;
}

export function formatStamp(ms) {
  if (!ms) return '--';
  const d = new Date(ms);
  const pad = (n) => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

export function workspaceRootId(folderPath) {
  return folderPath.endsWith('/') ? folderPath : `${folderPath}/`;
}

function convertNode(raw, rootId, parentRelative) {
  const relative = parentRelative ? `${parentRelative}/${raw.name}` : raw.name;
  const node = {
    id: `${rootId}${relative}`,
    name: raw.name,
    type: raw.type,
    size: raw.type === 'file' ? formatSize(raw.sizeBytes) : '--',
    modified: formatStamp(raw.modifiedMs),
  };
  if (raw.revisionCount) node.revisionCount = raw.revisionCount;
  if (raw.type === 'folder') {
    node.expanded = false;
    node.children = (raw.children ?? []).map((child) => convertNode(child, rootId, relative));
  }
  return node;
}

/** Build the single-root tree array FileTree expects from a raw listing. */
export function buildFileTree(rawChildren, rootId, rootLabel, modifiedMs) {
  return [
    {
      id: rootId,
      name: rootLabel,
      type: 'folder',
      isRoot: true,
      expanded: true,
      size: '--',
      modified: formatStamp(modifiedMs),
      children: (rawChildren ?? []).map((child) => convertNode(child, rootId, '')),
    },
  ];
}

export function buildWorkspaceTree(rawChildren, folderPath, modifiedMs) {
  const rootId = workspaceRootId(folderPath);
  return buildFileTree(rawChildren, rootId, rootId, modifiedMs);
}
