## BulletManager — 子弹管理器 Autoload（GDScript 接口层）
## 热路径由 C# BulletManagerCs 子节点驱动。
## 权威来源：architecture_design.md §4.2
##
## SoA 完整布局（BULLET_STRIDE=12）：
## [ x, y, vx, vy, lifetime, radius, base_damage, damage_mult, damage_type, owner_id, source_tags, acceleration ]
##   0  1   2   3      4       5          6              7           8          9          10           11
## 冷数据（pierce/bounce/homing/payload_id）→ _bullet_contexts: Dictionary
extends Node

const BULLET_STRIDE: int = 12   # 禁止裸整数 12（跨切片约束）
const MAX_BULLETS:   int = 2048 # 预分配 SoA 大小

# SoA 热数组（由 BulletManagerCs 直接读写）
var _data: PackedFloat32Array = PackedFloat32Array()
var _active_count: int = 0

# 冷数据（非热路径）
var _bullet_contexts: Dictionary = {}

# 敌人位置快照（homing 共用，由 _physics_process 帧头建立）
var _enemy_pos_snapshot: PackedVector2Array = PackedVector2Array()

var _cs_node: Node = null

func _ready() -> void:
	_data.resize(MAX_BULLETS * BULLET_STRIDE)
	_data.fill(0.0)

func _physics_process(delta: float) -> void:
	EnemyManager.fill_pos_snapshot(_enemy_pos_snapshot)
	if not _cs_node:
		_gd_integrate(delta)

# GDScript 回退路径（C# 未就绪时 / S0/S1 基线验证）
func _gd_integrate(delta: float) -> void:
	var i: int = 0
	while i < _active_count:
		var base: int = i * BULLET_STRIDE
		_data[base + 0] += _data[base + 2] * delta  # x += vx * dt
		_data[base + 1] += _data[base + 3] * delta  # y += vy * dt
		_data[base + 2] += _data[base + 11] * delta # vx += accel * dt
		_data[base + 3] += _data[base + 11] * delta # vy += accel * dt
		_data[base + 4] -= delta                     # lifetime -= dt
		if _data[base + 4] <= 0.0:
			_swap_and_pop(i)
		elif _check_collision(i, base):
			# 命中处理已在 _check_collision 内完成，子弹被回收
			pass  # _active_count 已减少，i 不递增
		else:
			i += 1

# S1 碰撞检测：数据驱动，使用 SpatialGrid 查询
# 命中后扣血；pierce_remaining=0 时回收子弹；返回 true 表示子弹已被回收
func _check_collision(bullet_idx: int, base: int) -> bool:
	var bx:     float = _data[base + 0]
	var by:     float = _data[base + 1]
	var br:     float = _data[base + 5]  # bullet radius
	var b_dmg:  float = _data[base + 6]  # base_damage
	var b_mult: float = _data[base + 7]  # damage_mult
	var b_type: int   = int(_data[base + 8])
	var b_own:  int   = int(_data[base + 9])
	var query_r: float = br + 16.0  # 16px = 敌人碰撞体估算半径
	var hits: PackedInt32Array = SpatialGrid.query_circle(Vector2(bx, by), query_r)
	if hits.is_empty():
		return false
	for entity_id in hits:
		var ene_pos: Vector2 = EnemyManager.get_pos_by_id(entity_id)
		if ene_pos == Vector2(-9999.0, -9999.0):
			continue
		var dx: float = bx - ene_pos.x
		var dy: float = by - ene_pos.y
		var dist_sq: float = dx * dx + dy * dy
		if dist_sq > query_r * query_r:
			continue
		# 命中：通过 DamageContextPool 发出伤害
		var ctx_id: int = DamageContextPool.acquire(b_dmg, b_mult, b_type, b_own, false, 0.0)
		EnemyManager.apply_damage_from_context(entity_id, ctx_id)
		DamageContextPool.release(ctx_id)
		var hit_pos: Vector2 = EnemyManager.get_pos_by_id(entity_id)
		if hit_pos == Vector2(-9999.0, -9999.0):
			hit_pos = Vector2(bx, by)
		VFXManager.play("hit_spark", hit_pos)
		EventBus.emit(EventID.BULLET_HIT, {"bullet_id": bullet_idx, "target_id": entity_id, "hit_pos": hit_pos})
		# S4: 命中施加状态 / 连击标记
		var cold: Dictionary = _bullet_contexts.get(bullet_idx, {})
		var status_id: int = int(cold.get("apply_status_id", -1))
		if status_id > 0:
			StatusManager.apply(entity_id, status_id, 1, -1.0, b_own)
		if cold.get("apply_combo_mark", false):
			StatusManager.apply(entity_id, StatusID.COMBO_MARK, 1, 2.0, b_own)
		# S3: 命中触发子荷载
		var payload_id: int = int(cold.get("on_hit_payload_id", -1))
		if payload_id >= 0:
			var parent_depth: int = int(cold.get("trigger_parent_depth", 0))
			SpellEvaluator.execute_sub(payload_id, hit_pos, b_own, parent_depth + 1)
		# pierce 处理
		var pierce: int = int(cold.get("pierce_remaining", 0))
		if pierce > 0:
			cold["pierce_remaining"] = pierce - 1
			_bullet_contexts[bullet_idx] = cold
			return false  # 穿透：子弹继续飞行
		_swap_and_pop(bullet_idx)
		return true  # 子弹已回收
	return false

func _swap_and_pop(idx: int) -> void:
	var last: int = _active_count - 1
	if idx != last:
		var base_idx:  int = idx  * BULLET_STRIDE
		var base_last: int = last * BULLET_STRIDE
		for s in BULLET_STRIDE:
			_data[base_idx + s] = _data[base_last + s]
		if _bullet_contexts.has(last):
			_bullet_contexts[idx] = _bullet_contexts[last]
			_bullet_contexts.erase(last)
		elif _bullet_contexts.has(idx):
			_bullet_contexts.erase(idx)
	_active_count -= 1

# ── 对外接口 ─────────────────────────────────────────────────────
## 生成子弹，返回 bullet_id（比 -1 表示满容）
## 参数附带冷数据：cold_data = {"on_hit_payload_id": int, "pierce_remaining": int, ...}
func spawn_bullet(pos: Vector2, vel: Vector2, lifetime: float, radius: float,
				  base_damage: float, damage_mult: float, damage_type: int,
				  owner_id: int, source_tags: int = 0, acceleration: float = 0.0,
				  cold_data: Dictionary = {}) -> int:
	if _active_count >= MAX_BULLETS:
		return -1
	var bullet_id: int = _active_count
	var base: int = bullet_id * BULLET_STRIDE
	_data[base + 0]  = pos.x
	_data[base + 1]  = pos.y
	_data[base + 2]  = vel.x
	_data[base + 3]  = vel.y
	_data[base + 4]  = lifetime
	_data[base + 5]  = radius
	_data[base + 6]  = base_damage
	_data[base + 7]  = damage_mult
	_data[base + 8]  = float(damage_type)
	_data[base + 9]  = float(owner_id)
	_data[base + 10] = float(source_tags)
	_data[base + 11] = acceleration
	if not cold_data.is_empty():
		_bullet_contexts[bullet_id] = cold_data
	_active_count += 1
	return bullet_id

## 提前回收：lifetime 置 0；C# 下帧 SoA 清理
func despawn_bullet(bullet_id: int) -> void:
	if bullet_id < 0 or bullet_id >= _active_count:
		return
	_data[bullet_id * BULLET_STRIDE + 4] = 0.0  # slot +4: lifetime

func get_active_count() -> int:
	return _active_count

## 渲染：将活跃子弹的 SoA 位置批量写入 MultiMesh（§4.4，SoA 索引 ↔ instance 索引共享）
## visible_instance_count 控制渲染数量，避免每帧重分配 instance_count
func sync_multimesh(mm: MultiMesh) -> void:
	if mm == null:
		return
	var n: int = min(_active_count, mm.instance_count)
	mm.visible_instance_count = n
	for i in n:
		var base: int = i * BULLET_STRIDE
		var r: float = _data[base + 5]
		mm.set_instance_transform_2d(i, Transform2D(
			0.0, Vector2(r * 2.0, r * 2.0), 0.0,
			Vector2(_data[base + 0], _data[base + 1])))

func get_nearest_enemy_pos(origin: Vector2, max_dist: float = 9999.0) -> Vector2:
	return EnemyManager.get_nearest_pos(origin, max_dist)

func reset() -> void:
	_active_count = 0
	_data.fill(0.0)
	_bullet_contexts.clear()
