using System;
using Unity.Mathematics;
using UnityEngine;

[CreateAssetMenu(menuName = "Actions/Retreat")]
public class RetreatAction : EnemyAction
{
    [SerializeField] private float retreatDistance = 4f;
    [SerializeField] private float tacticalRetreatDistance = 3f;
    public override float CalculateUtility(EnemyDecisionContext ctx)
    {
        //stop retreating if we are far away from the player.
        if (ctx.DistanceToPlayer > retreatDistance) return 0f;
        // 1. Health Logic (Existing: Low Health = Want to Retreat)
        float healthFactor = Mathf.InverseLerp(0, ctx.Entity.health.GetMaxHealth(), ctx.Entity.health.CurrentHealth);
        float lowHealthUrgency = 1f - Mathf.Clamp01(healthFactor);
        
        // 2. Tactical Logic (New: Just Attacked + Too Close = Want to Retreat)
        // Check if we are currently in the cooldown period
        float timeSinceAttack = ctx.TimeSinceLastAttack;
        float cooldown = ctx.Config.attackCooldown;
        
        // High urgency immediately after attack, fading to 0 as cooldown ends
        float postAttackUrgency = 1f - Mathf.Clamp01(timeSinceAttack / cooldown);
        
        // Only retreat if we are actually closer than we want to be
        // If we are already far away, we don't need to run further back
        float proximityFactor = 1f - Mathf.Clamp01(ctx.DistanceToPlayer / tacticalRetreatDistance);
        
        // Calculate the Tactical Score
        float tacticalScore = postAttackUrgency * proximityFactor;
        
        // 3. Base Logic
        float attackBias = (!ctx.Entity.Brain.Combat.IsAttacking) ? 0.1f : 0.0f; 
        
        // Combine: We retreat if we are dying OR if we need to back off tactically
        // I increased the weights so this action can actually win against Approach
        float utility = 0.1f + 
                        (lowHealthUrgency * 0.8f) + 
                        (tacticalScore * 1.5f) + // Strong weight to override Approach
                        attackBias;

        return Mathf.Clamp01(utility);
    }
    
    public override void Execute(EnemyBrain brain, EnemyDecisionContext ctx)
    {
        brain.Retreat();
        brain.animationBridge.UpdateApproachState(true);
        brain.animationBridge.UpdateIdleState(false);
    }
}
