import { getStraightPath, getSmoothStepPath } from 'reactflow';

const DEFAULT_FIXED_LENGTH = 150;

/**
 * 与流程设计器一致的边路径计算：支持固定线段长度与 smoothstep/straight 类型
 */
export function getFlowEdgePath(
  sourceX: number,
  sourceY: number,
  targetX: number,
  targetY: number,
  options?: { fixedLength?: number; type?: string }
): [string, number, number] {
  const fixedLength = options?.fixedLength ?? DEFAULT_FIXED_LENGTH;
  const edgeType = options?.type || 'straight';

  const dx = targetX - sourceX;
  const dy = targetY - sourceY;
  const actualDistance = Math.sqrt(dx * dx + dy * dy);

  let adjustedSourceX = sourceX;
  let adjustedSourceY = sourceY;
  let adjustedTargetX = targetX;
  let adjustedTargetY = targetY;

  if (fixedLength > 0 && actualDistance > fixedLength && actualDistance > 0.001) {
    const unitX = dx / actualDistance;
    const unitY = dy / actualDistance;
    const shortenDistance = (actualDistance - fixedLength) / 2;
    adjustedSourceX = sourceX + unitX * shortenDistance;
    adjustedSourceY = sourceY + unitY * shortenDistance;
    adjustedTargetX = targetX - unitX * shortenDistance;
    adjustedTargetY = targetY - unitY * shortenDistance;
  }

  if (edgeType === 'smoothstep') {
    return getSmoothStepPath({
      sourceX: adjustedSourceX,
      sourceY: adjustedSourceY,
      targetX: adjustedTargetX,
      targetY: adjustedTargetY,
      borderRadius: 15,
    });
  }
  return getStraightPath({
    sourceX: adjustedSourceX,
    sourceY: adjustedSourceY,
    targetX: adjustedTargetX,
    targetY: adjustedTargetY,
  });
}

export const FLOW_EDGE_DEFAULT_FIXED_LENGTH = DEFAULT_FIXED_LENGTH;
