using System.Collections.Generic;
using CounterDrone.Core.Algorithms;

namespace CounterDrone.Core.Simulation
{
    /// <summary>探测设备运行时实体。
    /// 持有 DetectionSource 静态参数 + 每无人机的探测状态机（Undetected ⇄ Detected）。
    /// Tick 扫描飞行无人机，首次进入探测范围 → 状态 Undetected→Detected，触发事件。
    /// 离开范围 → 回退 Undetected（决策 1）。
    /// 再次进入 → 重新置 Detected 并再次触发 TargetDetected。</summary>
    public class DetectionEntity
    {
        public string Id { get; }
        public DetectionSource Source { get; }
        public string? ModelId { get; }
        public float PosX => Source.Position.X;
        public float PosY => Source.Position.Y;
        public float PosZ => Source.Position.Z;

        /// <summary>每无人机 Id → 探测状态（true=Detected, false=Undetected）</summary>
        private readonly Dictionary<string, bool> _droneStates = new();

        public DetectionEntity(string id, DetectionSource source, string? modelId = null)
        {
            Id = id;
            Source = source;
            ModelId = modelId;
        }

        /// <summary>检查目标是否在本设备探测范围内（3D 球冠判定）</summary>
        public bool IsInRange(float targetX, float targetY, float targetZ,
            float visibility, out float effectiveRange)
        {
            effectiveRange = DetectionCalculator.EffectiveRange(
                Source.RadarRange, Source.EORange, Source.IRRange, visibility);
            if (effectiveRange <= 0) return false;

            return DetectionCalculator.IsInCoverage(
                new Vector3(targetX, targetY, targetZ), Source.Position,
                effectiveRange,
                Source.MinElevation, Source.MaxElevation,
                Source.MinDetectAlt, Source.MaxDetectAlt);
        }

        /// <summary>更新探测状态。首次进入返回 true（触发事件）；离开返回 false；持续在范围内返回 null。</summary>
        public bool? UpdateState(string droneId, bool inRange)
        {
            bool wasDetected = _droneStates.TryGetValue(droneId, out var s) && s;

            if (inRange)
            {
                _droneStates[droneId] = true;
                return wasDetected ? null : true;  // 首次进入 → 触发事件
            }
            else
            {
                if (wasDetected)
                    _droneStates[droneId] = false;
                return null;
            }
        }

        /// <summary>获取该设备对某无人机的当前探测状态</summary>
        public bool IsDetected(string droneId)
            => _droneStates.TryGetValue(droneId, out var s) && s;
    }
}
