using System;
using CounterDrone.Core.Models;

namespace CounterDrone.Core.Algorithms
{
    /// <summary>毁伤评估——路径积分计算无人机穿过云团的路径长度（米），用于换算暴露时间</summary>
    public static class DamageAssessment
    {
        /// <summary>线段 (p1→p2) 在球体内的长度，换算为路径长度 (m)</summary>
        /// <returns>球体内的路径长度 (m)，0 表示未进入</returns>
        public static float PathInSphere(
            float p1x, float p1y, float p1z,
            float p2x, float p2y, float p2z,
            float cx, float cy, float cz, float radius)
        {
            float dx = p2x - p1x, dy = p2y - p1y, dz = p2z - p1z;
            float segLen = (float)Math.Sqrt(dx * dx + dy * dy + dz * dz);
            if (segLen < 0.0001f) return 0f;

            float fx = p1x - cx, fy = p1y - cy, fz = p1z - cz;

            // |p1 + t*d - c|² = r² → a*t² + 2b*t + c = 0
            float a = dx * dx + dy * dy + dz * dz;
            float b = dx * fx + dy * fy + dz * fz;
            float c = fx * fx + fy * fy + fz * fz - radius * radius;

            float disc = b * b - a * c;
            if (disc <= 0) return 0f;

            float sqrtDisc = (float)Math.Sqrt(disc);
            float t1 = (-b - sqrtDisc) / a;
            float t2 = (-b + sqrtDisc) / a;

            t1 = Math.Max(0f, t1);
            t2 = Math.Min(1f, t2);
            if (t1 >= t2) return 0f;

            return (t2 - t1) * segLen;
        }
    }
}
