using System;
using System.Numerics;

namespace NavisworksTransport.Utils.CoordinateSystem
{
    /// <summary>
    /// 真实物体在 Rail 路径下的尺寸语义解析。
    /// 先根据解释后的真实参考姿态解析 rail 轴约定，再使用：
    /// 1. rail 基姿态（零角度时对象与路径框架对齐后的宿主姿态）
    /// 2. 最终姿态（rail 基姿态再叠加宿主轴角度修正）
    /// 共同计算沿 rail forward/side/normal 的有效尺寸。
    ///
    /// 关键点：
    /// - 这里不能只吃“角度修正”本身；否则双轴旋转时会漏掉 rail 基姿态语义。
    /// - 目标语义轴来自 rail 基姿态，而不是宿主世界轴。
    /// </summary>
    public static class RealObjectRailExtentResolver
    {
        public static bool TryResolveProjectedSemanticExtents(
            Vector3 referenceAxisX,
            Vector3 referenceAxisY,
            Vector3 referenceAxisZ,
            LocalAxisDirection hostUpLocalAxis,
            Vector3 desiredForward,
            CoordinateSystemType hostType,
            double forwardSize,
            double sideSize,
            double upSize,
            Quaternion baselineHostQuaternion,
            Quaternion finalHostQuaternion,
            out ModelAxisConvention convention,
            out (double forwardExtent, double sideExtent, double upExtent) extents)
        {
            convention = null;
            extents = (0.0, 0.0, 0.0);

            if (!RealObjectRailAxisConventionResolver.TryResolve(
                referenceAxisX,
                referenceAxisY,
                referenceAxisZ,
                hostUpLocalAxis,
                desiredForward,
                hostType,
                out convention,
                out _,
                out _,
                out _,
                out _))
            {
                return false;
            }

            Vector3 targetForward = Vector3.Normalize(Vector3.Transform(convention.ForwardUnitVector, baselineHostQuaternion));
            Vector3 targetUp = Vector3.Normalize(Vector3.Transform(convention.UpUnitVector, baselineHostQuaternion));
            extents = RealObjectProjectedExtentResolver.CalculateProjectedSemanticExtents(
                convention,
                forwardSize,
                sideSize,
                upSize,
                baselineHostQuaternion,
                finalHostQuaternion,
                targetForward,
                targetUp);
            return true;
        }
    }
}
