BotAI.cs
using Sandbox;
using System;
using System.Collections.Generic;
using System.Linq;

public sealed class BotAI : Component
{
    private const float TargetSearchInterval = 0.35f;

    [Property] public bool IsSurvivorTeammate { get; set; } = false;
    [Property] public float Speed { get; set; } = 220f;
    [Property] public float SurvivorSpeed { get; set; } = 360f;
    [Property] public float AttackRange { get; set; } = 220f;

    private CharacterController _cc;
    private PushAbility _push;
    private ManeuverAbility _maneuver;
    private PlayerHealth _health;
    private NavMeshAgent _navMeshAgent;
    private GameObject _friendlyLightObj;

    [Sync] private TimeUntil _nextDecision { get; set; }
    private Vector3 _moveDir;

    private GameObject _cachedTarget;
    [Sync] private TimeSince _timeSinceTargetCheck { get; set; } = 1f;

    // Survivor AI state
    private TimeSince _timeSincePathCalc = 1f;
    private List<Vector3> _navPoints = new();
    private int _navPointIndex = 0;
    private PlayerHealth _rescueTarget;
    private float _reviveHoldTimer = 0f;

    protected override void OnAwake()
    {
        _cc = Components.Get<CharacterController>();
        _push = Components.Get<PushAbility>();
        _maneuver = Components.Get<ManeuverAbility>();
        _health = Components.Get<PlayerHealth>();
        _navMeshAgent = Components.Get<NavMeshAgent>();
    }

    protected override void OnStart()
    {
        if ( IsSurvivorTeammate )
        {
            if ( !_navMeshAgent.IsValid() )
            {
                _navMeshAgent = Components.Create<NavMeshAgent>();
            }
            if ( _navMeshAgent.IsValid() )
            {
                // We steer CharacterController smoothly along NavMesh waypoints so SpringPad/JumpPad vertical launches work naturally
                _navMeshAgent.UpdatePosition = false;
                _navMeshAgent.UpdateRotation = false;
            }

            if ( !_friendlyLightObj.IsValid() )
            {
                _friendlyLightObj = Scene.CreateObject();
                _friendlyLightObj.Name = "SurvivorBot_TealLight";
                _friendlyLightObj.SetParent( GameObject );
                _friendlyLightObj.LocalPosition = Vector3.Up * 55f;

                var pt = _friendlyLightObj.Components.Create<PointLight>();
                pt.LightColor = Color.FromRgb( 0x2dd4bf );
                pt.Radius = 210f;
                pt.Intensity = 1.6f;
                pt.Shadows = false;
                pt.FogStrength = 1.2f;
            }
        }
    }

    protected override void OnUpdate()
    {
        if ( IsProxy ) return;

        if ( IsSurvivorTeammate )
        {
            UpdateSurvivorTeammate();
            return;
        }

        UpdateSumoBot();
    }

    private void UpdateSumoBot()
    {
        if ( _timeSinceTargetCheck > TargetSearchInterval )
        {
            _timeSinceTargetCheck = 0;
            _cachedTarget = FindTarget();
        }

        if ( _cachedTarget.IsValid() )
        {
            _moveDir = (_cachedTarget.WorldPosition - WorldPosition).WithZ( 0 ).Normal;

            if ( _cc.IsValid() )
            {
                _cc.Velocity = _moveDir * Speed;
                WorldRotation = Rotation.LookAt( _moveDir );
            }

            float dist = Vector3.DistanceBetween( WorldPosition, _cachedTarget.WorldPosition );
            if ( dist <= AttackRange && _push.IsValid() && _push.IsReady )
            {
                _push.TryExecuteBotPush();
            }
        }
        else
        {
            if ( _nextDecision )
            {
                _nextDecision = Game.Random.Float( 2f, 4f );
                float angle = Game.Random.Float( 0f, MathF.PI * 2f );
                _moveDir = new Vector3( MathF.Cos( angle ), MathF.Sin( angle ), 0f );
            }

            if ( _cc.IsValid() )
            {
                _cc.Velocity = _moveDir * (Speed * 0.6f);
            }
        }

        if ( _cc.IsValid() && !_cc.IsOnGround && _maneuver.IsValid() && _maneuver.IsDashReady )
        {
            _maneuver.TryExecuteBotDash( -_cc.Velocity.Normal );
        }
    }

    private void UpdateSurvivorTeammate()
    {
        if ( !_cc.IsValid() ) return;

        // If downed or dead, stop AI steering
        if ( _health.IsValid() && ( _health.IsDead || _health.IsDowned ) )
        {
            _reviveHoldTimer = 0f;
            _rescueTarget = null;
            return;
        }

        // Check nearest Nextbot threat
        var bots = Scene.GetAllComponents<NextbotAI>()
            .Where( b => b.IsValid() && b.GameObject.IsValid() && b.GameObject.Enabled && !b.IsStunned )
            .ToList();

        float nearestBotDist = float.MaxValue;
        NextbotAI nearestBot = null;
        foreach ( var b in bots )
        {
            float d = Vector3.DistanceBetween( WorldPosition, b.WorldPosition );
            if ( d < nearestBotDist )
            {
                nearestBotDist = d;
                nearestBot = b;
            }
        }

        // 1. PRIORITY: RESCUE DOWNED TEAMMATES (prefer human players first)
        _rescueTarget = FindBestDownedTeammate();
        if ( _rescueTarget.IsValid() )
        {
            float distToDowned = Vector3.DistanceBetween( WorldPosition, _rescueTarget.WorldPosition );
            if ( distToDowned <= 125f )
            {
                // Hold position & revive unless Nextbot is directly on top of us
                if ( nearestBotDist > 110f )
                {
                    ApplyGravityAndVelocity( Vector3.Zero );
                    WorldRotation = Rotation.LookAt( (_rescueTarget.WorldPosition - WorldPosition).WithZ( 0 ).Normal );

                    float mult = (RoundMutatorManager.Instance?.ActiveMutator == RoundMutatorType.Overclocked) ? 2.0f : 1.0f;
                    _reviveHoldTimer += Time.Delta * mult;

                    if ( _reviveHoldTimer >= _rescueTarget.ReviveDuration )
                    {
                        _rescueTarget.RequestRevive( GameObject );
                        _reviveHoldTimer = 0f;
                        _rescueTarget = null;
                    }
                    return;
                }
                else
                {
                    _reviveHoldTimer = 0f;
                }
            }
            else
            {
                _reviveHoldTimer = 0f;
                MoveTowardsNavTarget( _rescueTarget.WorldPosition, SurvivorSpeed * 1.15f );
                return;
            }
        }
        else
        {
            _reviveHoldTimer = 0f;
        }

        // 2. PRIORITY: EVADE NEARBY NEXTBOTS (and use SpringPads / JumpPads to escape!)
        if ( nearestBot.IsValid() && nearestBotDist < 680f )
        {
            // Look for an escape SpringPad or JumpPad nearby that leads away from danger
            Vector3 escapePadPos = FindUsefulLaunchPad( nearestBot.WorldPosition );
            if ( escapePadPos != Vector3.Zero )
            {
                MoveTowardsNavTarget( escapePadPos, SurvivorSpeed * 1.1f );
                return;
            }

            // Compute weighted flee direction away from nearby Nextbots
            Vector3 fleeDir = Vector3.Zero;
            foreach ( var b in bots )
            {
                float d = Vector3.DistanceBetween( WorldPosition, b.WorldPosition );
                if ( d < 750f )
                {
                    Vector3 away = (WorldPosition - b.WorldPosition).WithZ( 0 );
                    if ( away.LengthSquared > 0.01f )
                    {
                        fleeDir += away.Normal * (750f / MathF.Max( 60f, d ));
                    }
                }
            }

            // Gentle pull toward arena center/spawn so bot doesn't get cornered forever
            var spawnCenter = Scene.GetAllComponents<SpawnPoint>().FirstOrDefault()?.WorldPosition ?? Vector3.Zero;
            fleeDir += (spawnCenter - WorldPosition).WithZ( 0 ).Normal * 0.35f;

            if ( fleeDir.LengthSquared > 0.01f )
            {
                Vector3 fleeGoal = WorldPosition + fleeDir.Normal * 360f;
                MoveTowardsNavTarget( fleeGoal, SurvivorSpeed );
                return;
            }
        }

        // 3. PRIORITY: EXTRACTION FINALE (reach Extraction Beacon in Final 30s)
        if ( EvadeRoundManager.Instance != null && EvadeRoundManager.Instance.IsApexClimaxActive &&
             Teleporter.ActiveExtractionBeacon.IsValid() && Teleporter.ActiveExtractionBeacon.IsExtractionActive )
        {
            Vector3 extractPos = Teleporter.ActiveExtractionBeacon.WorldPosition;
            if ( Vector3.DistanceBetween( WorldPosition, extractPos ) > 95f )
            {
                MoveTowardsNavTarget( extractPos, SurvivorSpeed * 1.05f );
                return;
            }
            ApplyGravityAndVelocity( Vector3.Zero );
            return;
        }

        // 4. DEFAULT: ESCORT HUMAN PLAYER / PATROL
        var human = Scene.GetAllComponents<PlayerController>()
            .FirstOrDefault( p => p.IsValid() && p.GameObject.Enabled && !p.IsDead() && !p.IsDowned() );
        if ( human.IsValid() )
        {
            float distHuman = Vector3.DistanceBetween( WorldPosition, human.WorldPosition );
            if ( distHuman > 360f )
            {
                MoveTowardsNavTarget( human.WorldPosition, SurvivorSpeed * 0.9f );
                return;
            }
        }

        // Gentle idle roam
        if ( _nextDecision )
        {
            _nextDecision = Game.Random.Float( 2f, 4f );
            float angle = Game.Random.Float( 0f, MathF.PI * 2f );
            _moveDir = new Vector3( MathF.Cos( angle ), MathF.Sin( angle ), 0f );
        }
        ApplyGravityAndVelocity( _moveDir * (SurvivorSpeed * 0.45f) );
    }

    private PlayerHealth FindBestDownedTeammate()
    {
        PlayerHealth best = null;
        float bestScore = float.MaxValue;

        foreach ( var p in PlayerHealth.ActiveDownedPlayers )
        {
            if ( !p.IsValid() || p == _health || !p.IsDowned ) continue;
            float dist = Vector3.DistanceBetween( WorldPosition, p.WorldPosition );
            // Prioritize human players strongly over other AI bots
            bool isHuman = p.Components.Get<PlayerController>().IsValid();
            float score = isHuman ? dist * 0.25f : dist;
            if ( score < bestScore )
            {
                bestScore = score;
                best = p;
            }
        }
        return best;
    }

    private Vector3 FindUsefulLaunchPad( Vector3 threatPos )
    {
        Vector3 bestPos = Vector3.Zero;
        float bestDist = 380f;

        foreach ( var spring in Scene.GetAllComponents<SpringPad>() )
        {
            if ( !spring.IsValid() || !spring.GameObject.Enabled ) continue;
            float d = Vector3.DistanceBetween( WorldPosition, spring.WorldPosition );
            float threatToPad = Vector3.DistanceBetween( threatPos, spring.WorldPosition );
            if ( d < bestDist && threatToPad > d * 0.8f )
            {
                bestDist = d;
                bestPos = spring.WorldPosition;
            }
        }

        foreach ( var jumpPad in Scene.GetAllComponents<JumpPad>() )
        {
            if ( !jumpPad.IsValid() || !jumpPad.GameObject.Enabled ) continue;
            float d = Vector3.DistanceBetween( WorldPosition, jumpPad.WorldPosition );
            float threatToPad = Vector3.DistanceBetween( threatPos, jumpPad.WorldPosition );
            if ( d < bestDist && threatToPad > d * 0.8f )
            {
                bestDist = d;
                bestPos = jumpPad.WorldPosition;
            }
        }

        return bestPos;
    }

    private void MoveTowardsNavTarget( Vector3 targetPos, float moveSpeed )
    {
        if ( _timeSincePathCalc > 0.25f )
        {
            _timeSincePathCalc = 0f;
            RecalculateNavPath( targetPos );
        }

        Vector3 steerTarget = targetPos;
        if ( _navPoints.Count > 0 )
        {
            while ( _navPointIndex < _navPoints.Count &&
                    Vector3.DistanceBetween( WorldPosition.WithZ( 0 ), _navPoints[_navPointIndex].WithZ( 0 ) ) < 45f )
            {
                _navPointIndex++;
            }

            if ( _navPointIndex < _navPoints.Count )
            {
                steerTarget = _navPoints[_navPointIndex];
            }
        }

        Vector3 dir = (steerTarget - WorldPosition).WithZ( 0 );
        if ( dir.LengthSquared > 0.01f )
        {
            _moveDir = dir.Normal;
            WorldRotation = Rotation.LookAt( _moveDir );
        }

        // Jump over small step/obstacle in front if grounded
        if ( _cc.IsOnGround )
        {
            var obstacleTr = Scene.Trace.Ray( WorldPosition + Vector3.Up * 18f, WorldPosition + Vector3.Up * 18f + _moveDir * 42f )
                .IgnoreGameObjectHierarchy( GameObject )
                .Run();

            if ( obstacleTr.Hit )
            {
                _cc.Velocity = _cc.Velocity.WithZ( 310f );
            }
        }

        ApplyGravityAndVelocity( _moveDir * moveSpeed );
    }

    private void ApplyGravityAndVelocity( Vector3 horizontalVel )
    {
        if ( !_cc.IsValid() ) return;

        float zVel = _cc.IsOnGround ? MathF.Max( _cc.Velocity.z, -50f ) : (_cc.Velocity.z - 800f * Time.Delta);
        _cc.Velocity = horizontalVel.WithZ( zVel );
        _cc.Move();
    }

    private void RecalculateNavPath( Vector3 targetPos )
    {
        _navPoints.Clear();
        _navPointIndex = 0;

        if ( !_navMeshAgent.IsValid() || Scene.NavMesh == null || !Scene.NavMesh.IsEnabled || Scene.NavMesh.IsGenerating )
            return;

        var path = Scene.NavMesh.CalculatePath( new()
        {
            Start = WorldPosition,
            Target = targetPos,
            Agent = _navMeshAgent
        } );

        if ( path.IsValid && path.Points.Count > 0 )
        {
            _navPoints.AddRange( path.Points.Select( p => p.Position ) );
        }
    }

    private GameObject FindTarget()
    {
        float minDistance = float.MaxValue;
        GameObject closest = null;
        Vector3 myPos = WorldPosition;

        var controllers = Scene.GetAllComponents<CharacterController>();
        foreach ( var c in controllers )
        {
            if ( !c.IsValid() || c.GameObject == GameObject || !c.GameObject.IsValid() ) continue;

            float dist = Vector3.DistanceBetween( myPos, c.WorldPosition );
            if ( dist < minDistance )
            {
                minDistance = dist;
                closest = c.GameObject;
            }
        }

        return closest;
    }

    protected override void OnDestroy()
    {
        if ( _friendlyLightObj.IsValid() )
        {
            _friendlyLightObj.Destroy();
            _friendlyLightObj = null;
        }
        base.OnDestroy();
    }
}