import { useQuery } from '@tanstack/react-query';
import { fetchCodeTree } from '@/api/code';

export interface TreemapNode {
  name: string;
  path?: string;
  value?: number;
  children?: TreemapNode[];
}

/**
 * The backend returns a nested dict-of-dicts:
 *   { "src": { "components": { "App.tsx": { id, language, lines_of_code } } } }
 *
 * Leaf nodes have an "id" key (file records).
 * Directory nodes are plain objects whose values are children.
 */
function isLeaf(obj: Record<string, unknown>): boolean {
  return 'id' in obj;
}

function dictToTree(name: string, obj: Record<string, unknown>, parentPath: string): TreemapNode {
  if (isLeaf(obj)) {
    const loc = typeof obj.lines_of_code === 'number' ? obj.lines_of_code : 1;
    return {
      name,
      path: parentPath ? `${parentPath}/${name}` : name,
      value: loc,
    };
  }

  const children: TreemapNode[] = [];
  for (const [key, value] of Object.entries(obj)) {
    if (value && typeof value === 'object') {
      const childPath = parentPath ? `${parentPath}/${name}` : name;
      children.push(dictToTree(key, value as Record<string, unknown>, childPath));
    }
  }

  return {
    name,
    path: parentPath ? `${parentPath}/${name}` : name,
    children: children.length > 0 ? children : undefined,
    value: children.length === 0 ? 1 : undefined,
  };
}

export function useTreemapData(prefix?: string) {
  return useQuery({
    queryKey: ['code', 'tree', { prefix }],
    queryFn: () => fetchCodeTree(prefix),
    select(raw: unknown): TreemapNode {
      const data = (raw && typeof raw === 'object') ? raw as Record<string, unknown> : {};
      return dictToTree('root', data, '');
    },
  });
}
