# client/src/client_enemy_manager.py
import pygame
from client.src.enemy import Enemy

class ClientEnemyManager:
    def __init__(self):
        self.enemies = {}  # key: enemy id, value: Enemy instance
   
    def add_enemy(self, enemy_data):
        """
        Handles the 'enemy_spawn' event or initial enemy data.
        Creates a new enemy sprite with full data (including actions).
        """
        enemy_id = enemy_data.get("id")
        if not enemy_id:
            return  # Ignore if no ID
        
        if enemy_id in self.enemies:
            # Enemy already exists, just update it
            print(f"[Client] Enemy {enemy_id} already exists, updating instead of spawning")
            self.enemies[enemy_id].sync_state(enemy_data)
            return
       
        # Create new enemy with spawn data (includes actions)
        self.enemies[enemy_id] = Enemy(enemy_data)
        print(f"[Client] Spawned enemy: {enemy_data.get('name')} (ID: {enemy_id})")
    
    def update_enemy(self, enemy_data):
        """
        Handles the 'enemy_update' event.
        Updates an existing enemy's position/state (no actions in update data).
        """
        enemy_id = enemy_data.get("id")
        if not enemy_id:
            return
        
        enemy = self.enemies.get(enemy_id)
        if enemy:
            enemy.sync_state(enemy_data)
        else:
            # This shouldn't happen, but handle it gracefully
            print(f"[Warning] Received update for unknown enemy {enemy_id}, ignoring")
    
    def remove_enemy(self, enemy_id):
        """
        Handles the 'enemy_death' event.
        Removes an enemy sprite.
        """
        if enemy_id in self.enemies:
            del self.enemies[enemy_id]
            print(f"[Client] Removed enemy: (ID: {enemy_id})")
    
    def update(self, dt, player=None):
        """Update all enemies (movement interpolation, animation)."""
        for enemy in self.enemies.values():
            enemy.update(dt)
    
    def draw(self, virtual_surface, cam_x, cam_y):
        # Create a snapshot of the enemies to avoid RuntimeError
        for enemy in list(self.enemies.values()):
            enemy.draw(virtual_surface, cam_x, cam_y)