using System.Collections.Generic;
using System.Text;
using YachtDice.Modifiers.Core;

namespace YachtDice.Modifiers.Pipeline
{
    public class PipelineTrace
    {
        public TriggerType Trigger;
        public readonly List<TraceEntry> Entries = new();

        public struct TraceEntry
        {
            public string ModifierId;
            public string BehaviorName;
            public bool ConditionsPassed;
            public string FailedCondition;
            public string EffectApplied;
            public ModifierPhase Phase;
        }

        public void AddConditionResult(string modifierId, string behaviorName, bool passed, string failedCondition = null)
        {
            Entries.Add(new TraceEntry
            {
                ModifierId = modifierId,
                BehaviorName = behaviorName,
                ConditionsPassed = passed,
                FailedCondition = failedCondition,
            });
        }

        public void AddEffectApplied(string modifierId, string effectName, ModifierPhase phase)
        {
            Entries.Add(new TraceEntry
            {
                ModifierId = modifierId,
                EffectApplied = effectName,
                Phase = phase,
                ConditionsPassed = true,
            });
        }

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.AppendLine($"[ModifierPipeline] Trigger: {Trigger}");
            for (int i = 0; i < Entries.Count; i++)
            {
                var e = Entries[i];
                if (e.EffectApplied != null)
                {
                    sb.AppendLine($"  EFFECT [{e.Phase}] {e.ModifierId} -> {e.EffectApplied}");
                }
                else if (e.ConditionsPassed)
                {
                    sb.AppendLine($"  PASS {e.ModifierId} / {e.BehaviorName}");
                }
                else
                {
                    sb.AppendLine($"  FAIL {e.ModifierId} / {e.BehaviorName} (failed: {e.FailedCondition})");
                }
            }
            return sb.ToString();
        }
    }
}
