// utils/graphUtils.ts

import { neo4jColorScheme } from '../graphConfig/graphConfig';
import { D3Link, D3Node, Neo4jGraphData } from '../graphTypes/graphTypes';



export const getNodeColor = (labels: string[]): string => {
  const primaryLabel = labels[0];
  return neo4jColorScheme.nodeColors[primaryLabel as keyof typeof neo4jColorScheme.nodeColors] 
    || neo4jColorScheme.nodeColors.default;
};

export const getNodeDisplayName = (node: D3Node): string => {
  // Priority: name > title > id > first label
  return node.properties.name 
    || node.properties.title 
    || node.properties.id 
    || node.labels[0] 
    || node.id;
};

export const prepareGraphData = (graphData: Neo4jGraphData) => {
  const nodes: D3Node[] = [...graphData.nodes];
  const links: D3Link[] = graphData.relationships.map(rel => ({
    ...rel,
    source: rel.startNodeId,
    target: rel.endNodeId
  }));

  return { nodes, links };
};

export const formatPropertyValue = (value: any): string => {
  if (value === null || value === undefined) return '';
  if (typeof value === 'object') return JSON.stringify(value);
  if (typeof value === 'boolean') return value ? 'true' : 'false';
  return String(value);
};

export const truncateText = (text: string, maxLength: number = 20): string => {
  if (text.length <= maxLength) return text;
  return text.substring(0, maxLength - 3) + '...';
};

export const getNodeStats = (graphData: Neo4jGraphData) => {
  const labelCounts = graphData.nodes.reduce((acc, node) => {
    node.labels.forEach(label => {
      acc[label] = (acc[label] || 0) + 1;
    });
    return acc;
  }, {} as Record<string, number>);

  const relationshipCounts = graphData.relationships.reduce((acc, rel) => {
    acc[rel.type] = (acc[rel.type] || 0) + 1;
    return acc;
  }, {} as Record<string, number>);

  return {
    totalNodes: graphData.nodes.length,
    totalRelationships: graphData.relationships.length,
    labelCounts,
    relationshipCounts,
  };
};