extends Node

var entities: Dictionary = {}

func register(entity: Node, base: EnemyStats, scale: float = 1.0) -> void:
  var max_hp: float = base.max_health * scale
  var max_sh: float = base.max_shield * scale
  entities[entity] = {
    "base": base,
    "scale": scale,
    "health": max_hp,
    "max_health": max_hp,
    "health_regen": base.health_regen * scale,
    "shield": max_sh,
    "max_shield": max_sh,
    "shield_regen_delay": base.shield_regen_delay,
    "shield_regen_time": base.shield_regen_time,
    "shield_regen_timer": 0.0,
    "alive": true,
    "buff_damage": 1.0,
    "buff_heal": 1.0,
    "buff_shield": 1.0,
    "state": 0,
    "target": null,
    "spawn_position": Vector3.ZERO,
    "portal": null,
    "attack_timer": 0.0,
  }

func apply_scale(entity: Node, scale: float) -> void:
  if entity not in entities:
    return
  var data: Dictionary = entities[entity]
  var base: EnemyStats = data["base"]
  data["scale"] = scale
  data["max_health"] = base.max_health * scale
  data["health"] = data["max_health"]
  data["health_regen"] = base.health_regen * scale
  data["max_shield"] = base.max_shield * scale
  data["shield"] = data["max_shield"]
  EventBus.health_changed.emit(entity, data["health"], data["max_health"])
  if base.max_shield > 0:
    EventBus.shield_changed.emit(entity, data["shield"], data["max_shield"])

func deregister(entity: Node) -> void:
  entities.erase(entity)

func get_stat(entity: Node, key: String) -> Variant:
  if entity in entities:
    return entities[entity].get(key)
  return null

func set_stat(entity: Node, key: String, value: Variant) -> void:
  if entity in entities:
    entities[entity][key] = value

func get_base(entity: Node) -> EnemyStats:
  if entity in entities:
    return entities[entity]["base"]
  return null

func is_alive(entity: Node) -> bool:
  if entity in entities:
    return entities[entity]["alive"]
  return false

func set_health(entity: Node, value: float) -> void:
  if entity not in entities:
    return
  entities[entity]["health"] = value
  var max_health: float = entities[entity]["max_health"]
  EventBus.health_changed.emit(entity, value, max_health)
  if value <= 0 and entities[entity]["alive"]:
    entities[entity]["alive"] = false
    EventBus.entity_died.emit(entity)

func set_shield(entity: Node, value: float) -> void:
  if entity not in entities:
    return
  entities[entity]["shield"] = value
  var max_shield: float = entities[entity]["max_shield"]
  EventBus.shield_changed.emit(entity, value, max_shield)
