using System;
using System.Numerics;
using NavisworksTransport.Core;

namespace NavisworksTransport.Utils.CoordinateSystem
{
    /// <summary>
    /// 负责在 Canonical Space 中，将 Rail 路径参考点转换成动画跟踪中心点。
    /// 这层只处理纯数学偏移，不依赖 Navisworks API。
    /// </summary>
    public static class CanonicalRailOffsetResolver
    {
        public static double GetCenterTrackedOffset(PathRoute route, double objectHeight)
        {
            // 路径点本身已经是安装参考点（终点锚点）语义。
            // 动画跟踪中心只需要相对安装参考点沿轨道法向偏移半个高度，
            // 不能叠加任何“参考线 -> 锚点”旧语义偏移，否则会把终点/逐帧参考点重复平移。
            double halfHeightOffset = PathRoute.IsTopReferenceFaceForMountMode(route.RailMountMode)
                ? -objectHeight / 2.0
                : objectHeight / 2.0;
            return halfHeightOffset + route.RailNormalOffset;
        }

        public static Vector3 ResolveTrackedCenter(
            PathRoute route,
            Vector3 canonicalReferencePoint,
            RailLocalFrame localFrame,
            double objectHeight)
        {
            if (route == null || route.PathType != PathType.Rail)
            {
                return canonicalReferencePoint;
            }

            if (localFrame == null)
            {
                throw new ArgumentNullException(nameof(localFrame));
            }

            double centerOffset = GetCenterTrackedOffset(route, objectHeight);
            double referenceContactFactor = 0.5 - (centerOffset / objectHeight);
            return CanonicalTrackedPositionResolver.ResolveCenterFromContactReference(
                canonicalReferencePoint,
                localFrame.Normal,
                objectHeight,
                referenceContactFactor);
        }
    }
}
