using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CounterDrone.Core.Models;
using CounterDrone.Core.Simulation;

namespace CounterDrone.Core.Services
{
    public class ReportGenerator
    {
        public string Generate(TaskFullConfig config, List<SimEvent> events,
            Simulation.DroneStatus finalDroneStatus, float simulationDuration)
        {
            var sb = new StringBuilder();
            var platforms = config.Equipment.Where(e => e.EquipmentRole == (int)EquipmentRole.LaunchPlatform).ToList();
            var target = config.Targets.FirstOrDefault();
            var scene = config.Scene;
            var destroyed = events.Count(e => e.Type == SimEventType.DroneDestroyed);
            var reached = events.Count(e => e.Type == SimEventType.DroneReachedTarget);
            var intruded = events.Count(e => e.Type == SimEventType.ZoneIntruded);
            var totalDrones = config.Targets.Sum(t => t.Quantity);
            var result = DetermineInterceptResult(destroyed, reached + intruded, totalDrones);

            sb.AppendLine("# 仿真评估报告");
            sb.AppendLine();
            sb.AppendLine($"| 项目 | 值 |");
            sb.AppendLine($"|------|-----|");
            sb.AppendLine($"| 任务名称 | {config.Task.Name} |");
            sb.AppendLine($"| 任务编号 | {config.Task.TaskNumber} |");
            sb.AppendLine($"| 仿真耗时 | {simulationDuration:F1} 秒 |");
            sb.AppendLine($"| 气溶胶类型 | {TranslateAerosol((AerosolType)config.Cloud.AerosolType)} |");
            sb.AppendLine();

            // === 一、仿真结果 ===
            sb.AppendLine("## 一、仿真结果");
            sb.AppendLine();
            sb.AppendLine($"| 统计项 | 值 |");
            sb.AppendLine($"|--------|-----|");
            sb.AppendLine($"| 无人机总数 | {totalDrones} |");
            sb.AppendLine($"| 被摧毁 | {destroyed} |");
            sb.AppendLine($"| 到达目标 | {reached} |");
            sb.AppendLine($"| 侵入管控区 | {intruded} |");
            sb.AppendLine($"| 弹药发射 | {events.Count(e => e.Type == SimEventType.MunitionLaunched)} |");
            sb.AppendLine($"| 云团生成 | {events.Count(e => e.Type == SimEventType.CloudGenerated)} |");
            sb.AppendLine();
            sb.AppendLine($"**对抗结果**：{TranslateResult(result)}");
            sb.AppendLine();

            // === 二、作战环境 ===
            sb.AppendLine("## 二、作战环境");
            sb.AppendLine();
            sb.AppendLine($"| 参数 | 值 |");
            sb.AppendLine($"|------|-----|");
            sb.AppendLine($"| 天气 | {TranslateWeather((WeatherType)scene.WeatherType)} |");
            sb.AppendLine($"| 风速 | {scene.WindSpeed} m/s |");
            sb.AppendLine($"| 风向 | {scene.WindDirection} |");
            sb.AppendLine($"| 温度 | {scene.Temperature}°C |");
            sb.AppendLine($"| 能见度 | {scene.Visibility} m |");
            sb.AppendLine();

            // === 三、威胁目标 ===
            sb.AppendLine("## 三、威胁目标");
            sb.AppendLine();
            sb.AppendLine($"| 参数 | 值 |");
            sb.AppendLine($"|------|-----|");
            sb.AppendLine($"| 类型 | {TranslateTarget((TargetType)(target?.TargetType ?? 0))} |");
            sb.AppendLine($"| 数量 | {totalDrones} 架 |");
            sb.AppendLine($"| 速度 | {target?.TypicalSpeed ?? 0} km/h |");
            sb.AppendLine($"| 高度 | {target?.TypicalAltitude ?? 0} m |");
            sb.AppendLine($"| 动力 | {TranslatePower((PowerType)(target?.PowerType ?? 0))} |");
            sb.AppendLine();

            // === 四、推荐方案 ===
            if (config.Cloud.Source == "Algorithm" && config.Cloud.EstimatedProbability.HasValue)
            {
                sb.AppendLine("## 四、推荐方案");
                sb.AppendLine();
                sb.AppendLine($"| 参数 | 值 |");
                sb.AppendLine($"|------|-----|");
                sb.AppendLine($"| 发射方式 | {TranslateRelease((ReleaseMode)config.Cloud.ReleaseMode)} |");
                sb.AppendLine($"| 弹药数 | {config.Cloud.SalvoRounds} 发 |");
                sb.AppendLine($"| 云团间距 | {config.Cloud.SalvoSpacing:F0} m |");
                sb.AppendLine($"| 拦截概率 | {config.Cloud.EstimatedProbability.Value:P0} |");
                sb.AppendLine($"| 抛撒时机 | {config.Cloud.RecommendedTiming:F0}s |");
                sb.AppendLine();
            }

            // 构建 PlatformId → 火力单元 映射（去重，五和六共用）
            var platToEquip = new Dictionary<string, int>();
            var unitLaunchCounts = new Dictionary<int, int>();
            int platIdx = 1, unitNum = 0;
            for (int ei = 0; ei < config.Equipment.Count; ei++)
            {
                var eq = config.Equipment[ei];
                if (eq.EquipmentRole != (int)EquipmentRole.LaunchPlatform) continue;
                int channels = (eq.GunCount ?? 1) * (eq.ChannelsPerGun ?? 1);
                for (int j = 0; j < eq.Quantity; j++)
                {
                    unitNum++;
                    for (int c = 0; c < channels; c++)
                        platToEquip[$"plat_{platIdx++}"] = unitNum;
                }
            }
            foreach (var e in events.Where(e => e.Type == SimEventType.MunitionLaunched))
            {
                if (platToEquip.TryGetValue(e.SourceId, out var u))
                    unitLaunchCounts[u] = unitLaunchCounts.GetValueOrDefault(u, 0) + 1;
            }

            // === 五、我方部署 ===
            sb.AppendLine("## 五、我方部署");
            sb.AppendLine();
            sb.AppendLine($"| 火力单元 | 发射数 |");
            sb.AppendLine($"|------|------|");
            foreach (var kv in unitLaunchCounts.OrderBy(kv => kv.Key))
                sb.AppendLine($"| #{kv.Key} | {kv.Value} |");
            sb.AppendLine();

            // === 六、事件时序 ===
            sb.AppendLine("## 六、事件时序");
            sb.AppendLine();
            sb.AppendLine("| 时间(s) | 事件 | 详情 | 火力单元 |");
            sb.AppendLine("|---------|------|------|:------:|");
            int munitionIdx = 0, cloudIdx = 0;
            foreach (var e in events.OrderBy(e => e.OccurredAt))
            {
                string unitCell = e.Type == SimEventType.MunitionLaunched && platToEquip.TryGetValue(e.SourceId, out var u)
                    ? $"#{u}" : "-";
                var desc = e.Type switch
                {
                    SimEventType.MunitionLaunched => $"第 {++munitionIdx} 发",
                    SimEventType.CloudGenerated => $"云团 #{++cloudIdx}",
                    SimEventType.DroneDestroyed => "目标被摧毁",
                    SimEventType.DroneReachedTarget => "目标抵达终点",
                    SimEventType.ZoneIntruded => "侵入管控区",
                    SimEventType.SimulationEnd => "仿真结束",
                    _ => e.Description,
                };
                sb.AppendLine($"| {e.OccurredAt:F2} | {TranslateEvent(e.Type)} | {desc} | {unitCell} |");
            }
            sb.AppendLine();

            // === 七、时间线 ===
            var launchTime = events.Where(e => e.Type == SimEventType.MunitionLaunched).Select(e => e.OccurredAt).DefaultIfEmpty(0).Min();
            var cloudTime = events.Where(e => e.Type == SimEventType.CloudGenerated).Select(e => e.OccurredAt).DefaultIfEmpty(0).Min();
            var destroyTime = events.Where(e => e.Type == SimEventType.DroneDestroyed).Select(e => e.OccurredAt).DefaultIfEmpty(0).Min();
            sb.AppendLine("## 七、时间线");
            sb.AppendLine();
            sb.AppendLine($"| 阶段 | 时间 | 耗时 |");
            sb.AppendLine($"|------|------|------|");
            if (launchTime > 0)
                sb.AppendLine($"| 发射 → 云团生成 | {launchTime:F1}s → {cloudTime:F1}s | {(cloudTime - launchTime):F1}s（弹药飞行） |");
            if (destroyTime > 0)
                sb.AppendLine($"| 云团生成 → 击毁 | {cloudTime:F1}s → {destroyTime:F1}s | {(destroyTime - cloudTime):F1}s（暴露毁伤） |");
            sb.AppendLine($"| 总耗时 | 0 → {simulationDuration:F1}s | {simulationDuration:F1}s |");
            sb.AppendLine();

            return sb.ToString();
        }

        public InterceptResult DetermineInterceptResult(int destroyed, int reachedOrIntruded, int total)
        {
            if (total == 0) return InterceptResult.Failed;
            if (destroyed >= total) return InterceptResult.Success;
            if (destroyed > 0) return InterceptResult.Partial;
            return InterceptResult.Failed;
        }

        private static string TranslateResult(InterceptResult r) => r switch
        {
            InterceptResult.Success => "✅ 成功拦截",
            InterceptResult.Partial => "⚠️ 部分拦截",
            InterceptResult.Failed => "❌ 拦截失败",
            _ => "未知",
        };

        private static string TranslateAerosol(AerosolType t) => t switch
        {
            AerosolType.InertGas => "惰性气体（吸入式灭火）",
            AerosolType.ActiveMaterial => "活性材料（爆燃式）",
            AerosolType.ActiveFuel => "活性燃料（吸入式爆炸）",
            _ => t.ToString(),
        };

        private static string TranslateWeather(WeatherType w) => w switch
        {
            WeatherType.Sunny => "晴天", WeatherType.Overcast => "阴天",
            WeatherType.Fog => "雾天", WeatherType.Rain => "雨天",
            WeatherType.Night => "夜间", _ => w.ToString(),
        };

        private static string TranslateTarget(TargetType t) => t switch
        {
            TargetType.Rotor => "旋翼", TargetType.FixedWing => "固定翼",
            TargetType.Electric => "电推", TargetType.Piston => "活塞",
            TargetType.HighSpeed => "高速目标", _ => t.ToString(),
        };

        private static string TranslatePower(PowerType p) => p switch
        {
            PowerType.Electric => "电推式", PowerType.Piston => "活塞式",
            PowerType.Jet => "喷吸气式", _ => p.ToString(),
        };

        private static string TranslateRelease(ReleaseMode r) => r switch
        {
            ReleaseMode.Single => "单次齐射", ReleaseMode.Continuous => "连续释放",
            ReleaseMode.Pulse => "脉冲释放", _ => r.ToString(),
        };

        private static string TranslateEvent(SimEventType t) => t switch
        {
            SimEventType.MunitionLaunched => "🚀 弹药发射",
            SimEventType.CloudGenerated => "☁️ 云团生成",
            SimEventType.DroneDestroyed => "💥 目标击毁",
            SimEventType.DroneReachedTarget => "🏁 抵达目标",
            SimEventType.ZoneIntruded => "🚨 侵入管控区",
            SimEventType.SimulationEnd => "⏹️ 仿真结束",
            _ => t.ToString(),
        };
    }
}
