package com.zombie.game.systems;

import com.zombie.game.ecs.ECSWorld;
import com.zombie.game.ecs.System;
import com.zombie.game.ecs.components.Health;
import com.zombie.game.model.GameMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Random;

import static com.zombie.game.model.Constants.*;

/** Periodically spawns zombies at map spawn points / 定期在地图出生点生成僵尸 */
public class ZombieSpawnSystem implements System {
    private static final Logger logger = LoggerFactory.getLogger(ZombieSpawnSystem.class);
    private final Random random = new Random();
    private float spawnTimer = 0;

    @Override
    public void update(float dt, ECSWorld world) {
        spawnTimer += dt;
        if (spawnTimer < ZOMBIE_SPAWN_INTERVAL) return;
        spawnTimer -= ZOMBIE_SPAWN_INTERVAL;

        // Count alive zombies
        int aliveCount = 0;
        for (int entityId : world.getZombies()) {
            Health health = world.getHealths().get(entityId);
            if (health != null && health.isAlive()) {
                aliveCount++;
            }
        }

        if (aliveCount >= ZOMBIE_MAX_COUNT) return;

        // Pick a random spawn point
        GameMap map = world.getMap();
        List<int[]> spawns = map.getZombieSpawnPoints();
        if (spawns.isEmpty()) return;

        int[] sp = spawns.get(random.nextInt(spawns.size()));
        int newZombie = world.createZombieEntity(sp[0] + 0.5f, sp[1] + 0.5f);
        logger.info("Zombie spawned: id={} at ({}, {}), alive={}", newZombie, sp[0], sp[1], aliveCount + 1);
    }
}
