/**
 * Graph 布局算法 — 圆形布局 + 度数计算
 */

import type { GraphNode, GraphEdge, NodePosition } from './graphTypes';
import { NODE_BASE_RADIUS, NODE_CENTER_RADIUS } from './graphConstants';

/** 计算节点的连接度 (degree) */
export function getNodeDegree(nodeId: string, edges: GraphEdge[]): number {
  return edges.filter((e) => e.source === nodeId || e.target === nodeId).length;
}

/** 根据度数映射节点半径 — 连接越多越大 */
export function degreeToRadius(degree: number, isCenter: boolean): number {
  const base = isCenter ? NODE_CENTER_RADIUS : NODE_BASE_RADIUS;
  const bonus = Math.min(degree * 1.2, 10);
  return base + bonus;
}

/** 计算圆形布局位置 */
export function computeCircularLayout(
  nodes: GraphNode[],
  centerX: number,
  centerY: number,
  radius: number,
): Map<string, NodePosition> {
  const positions = new Map<string, NodePosition>();
  const count = nodes.length;
  if (count === 0) return positions;

  if (count === 1) {
    positions.set(nodes[0].id, { x: centerX, y: centerY, vx: 0, vy: 0 });
    return positions;
  }

  nodes.forEach((node, i) => {
    const angle = (2 * Math.PI * i) / count - Math.PI / 2;
    positions.set(node.id, {
      x: centerX + radius * Math.cos(angle),
      y: centerY + radius * Math.sin(angle),
      vx: 0,
      vy: 0,
    });
  });

  return positions;
}
