import { getBezierPath, getSmoothStepPath, Position, type EdgeProps } from '@vue-flow/core'

const EDGE_PADDING_BOTTOM = 130
const EDGE_PADDING_X = 40
const EDGE_BORDER_RADIUS = 16
const HANDLE_SIZE = 20

const isRightOfSourceHandle = (sourceX: number, targetX: number) =>
	sourceX - HANDLE_SIZE > targetX

export type EdgeRenderData = {
	segments: ReturnType<typeof getBezierPath>[]
	labelPosition: [number, number]
	isConnectorStraight: boolean
}

export function getEdgeRenderData(
	props: Pick<
		EdgeProps,
		'sourceX' | 'sourceY' | 'sourcePosition' | 'targetX' | 'targetY' | 'targetPosition'
	>
): EdgeRenderData {
	const { targetX, targetY, sourceX, sourceY, sourcePosition, targetPosition } = props
	const isConnectorStraight = sourceY === targetY

	// 正向连接或连接不在源节点右侧 → 使用 Bezier
	if (!isRightOfSourceHandle(sourceX, targetX)) {
		const segment = getBezierPath(props)
		return {
			segments: [segment],
			labelPosition: [segment[1], segment[2]],
			isConnectorStraight
		}
	}

	// 反向连接（目标在源左侧）→ 两段 SmoothStep 绕行
	const midX = (sourceX + targetX) / 2
	const midY = sourceY + EDGE_PADDING_BOTTOM

	const firstSegment = getSmoothStepPath({
		sourceX,
		sourceY,
		targetX: midX,
		targetY: midY,
		sourcePosition,
		targetPosition: Position.Right,
		borderRadius: EDGE_BORDER_RADIUS,
		offset: EDGE_PADDING_X
	})

	const secondSegment = getSmoothStepPath({
		sourceX: midX,
		sourceY: midY,
		targetX,
		targetY,
		sourcePosition: Position.Left,
		targetPosition,
		borderRadius: EDGE_BORDER_RADIUS,
		offset: EDGE_PADDING_X
	})

	return {
		segments: [firstSegment, secondSegment],
		labelPosition: [midX, midY],
		isConnectorStraight
	}
}
