using System;
using System.Collections.Generic;
using System.Numerics;

namespace NavisworksTransport.Utils.CoordinateSystem
{
    /// <summary>
    /// 真实物体 fragment 姿态解析入口（仅保留诊断用途）。
    ///
    /// 说明：真实物体姿态链已不依赖 fragment（0.18.2 起使用默认轴约定，
    /// forward=+X、up=宿主 up）。原 TryResolveFromModelItem /
    /// TryResolveFromFragmentMatrices（fragment 代表姿态解析链）已删除。
    /// 本类仅保留系统诊断面板（SystemManagementViewModel 方法5）使用的
    /// TryDetectDefaultUpAxis。
    /// </summary>
    public static class RealObjectReferencePoseResolver
    {
        /// <summary>
        /// 从 fragment 矩阵检测物体的默认 Up 轴（Y 或 Z 更贴近宿主 up）。
        /// </summary>
        public static bool TryDetectDefaultUpAxis(
            IReadOnlyCollection<double[]> fragmentMatrices,
            string hostUpAxis,
            out string detectedAxis,
            out float yAlignment,
            out float zAlignment)
        {
            detectedAxis = "Y";
            yAlignment = 0.0f;
            zAlignment = 0.0f;

            if (fragmentMatrices == null || fragmentMatrices.Count == 0)
            {
                return false;
            }

            if (!FragmentRepresentativePoseHelper.TryGetRepresentativeFrame(fragmentMatrices, out var rawFrame))
            {
                return false;
            }

            Vector3 hostUpVector = string.Equals(hostUpAxis, "Y", StringComparison.OrdinalIgnoreCase)
                ? Vector3.UnitY
                : Vector3.UnitZ;

            yAlignment = Math.Abs(Vector3.Dot(Vector3.Normalize(rawFrame.AxisY), hostUpVector));
            zAlignment = Math.Abs(Vector3.Dot(Vector3.Normalize(rawFrame.AxisZ), hostUpVector));
            detectedAxis = zAlignment > yAlignment ? "Z" : "Y";
            return true;
        }
    }
}
