extends Node

@onready var role_system: Node = get_node("../RoleSystem")
@onready var cooldown_system: Node = get_node("../CooldownSystem")

var _accum: float = 0.0

func _ready() -> void:
  if multiplayer.multiplayer_peer != null and not multiplayer.is_server() and not (multiplayer.multiplayer_peer is OfflineMultiplayerPeer):
    set_physics_process(false)
  else:
    set_physics_process(true)

func _physics_process(delta: float) -> void:
  if not multiplayer.is_server() and multiplayer.multiplayer_peer != null:
    return
  _accum += delta
  if _accum < 0.10:
    return
  _accum = 0.0
  for player in get_tree().get_nodes_in_group("player"):
    if not Stats.has(player):
      continue
    if int(Stats.get_stat(player, "health", 0.0)) <= 0:
      continue
    if not cooldown_system.is_aa_ready(player):
      continue
    var role: int = int(Stats.get_stat(player, "role", GameState.ROLE_DAMAGE))
    var set: AbilitySet = role_system.get_set(role)
    if set == null:
      continue
    var target: Node = _pick_target(player, set)
    if target == null:
      continue
    var dist: float = (player as Node3D).global_position.distance_to((target as Node3D).global_position)
    if dist > set.aa_range:
      continue
    var dmg_mult: float = float(Stats.get_stat(player, "buff_damage", 1.0))
    var heal_mult: float = float(Stats.get_stat(player, "buff_heal", 1.0))
    if set.aa_is_heal:
      EventBus.heal_requested.emit(player, target, set.aa_damage * heal_mult)
    else:
      EventBus.damage_requested.emit(player, target, set.aa_damage * dmg_mult, Element.NONE)
    cooldown_system.set_aa(player, float(Stats.get_stat(player, "aa_cooldown", 0.5)))

func _pick_target(player: Node, set: AbilitySet) -> Node:
  if set.aa_is_heal:
    var lowest: Node = null
    var lowest_pct: float = 2.0
    for ally in get_tree().get_nodes_in_group("player"):
      if not Stats.has(ally):
        continue
      var hp: float = float(Stats.get_stat(ally, "health", 0.0))
      var max_hp: float = float(Stats.get_stat(ally, "max_health", 1.0))
      if hp <= 0.0:
        continue
      var pct: float = hp / max_hp
      if pct < lowest_pct and (player as Node3D).global_position.distance_to((ally as Node3D).global_position) <= set.aa_range:
        lowest = ally
        lowest_pct = pct
    return lowest
  var current_var: Variant = (player as Node).get("current_target")
  if current_var != null and is_instance_valid(current_var) and current_var is Node and Stats.has(current_var):
    return current_var
  var nearest: Node = null
  var nearest_dist: float = INF
  for foe in Stats.entities_in_group(&"enemies"):
    if not is_instance_valid(foe):
      continue
    var d: float = (foe as Node3D).global_position.distance_to((player as Node3D).global_position)
    if d < nearest_dist and d <= set.aa_range:
      nearest = foe
      nearest_dist = d
  return nearest
