import os

class Graphics():
    def load_assets(self):
        print("Loading graphics assets...")
        self.tunnel = self.render_engine.load_image("Rat/BMP_TUNNEL.png", surface=True)
        self.grasses = [self.render_engine.load_image(f"Rat/BMP_1_GRASS_{i+1}.png", surface=True) for i in range(4)]
        self.rat_assets = {}
        self.rat_assets_textures = {}
        self.rat_image_sizes = {}  # Pre-cache image sizes
        self.bomb_assets = {}
        
        for sex in ["MALE", "FEMALE", "BABY"]:
            self.rat_assets[sex] = {}
            for direction in ["UP", "DOWN", "LEFT", "RIGHT"]:
                self.rat_assets[sex][direction] = self.render_engine.load_image(f"Rat/BMP_{sex}_{direction}.png", transparent_color=(128, 128, 128))
        
        # Load textures and pre-cache sizes
        for sex in ["MALE", "FEMALE", "BABY"]:
            self.rat_assets_textures[sex] = {}
            self.rat_image_sizes[sex] = {}
            for direction in ["UP", "DOWN", "LEFT", "RIGHT"]:
                texture = self.render_engine.load_image(f"Rat/BMP_{sex}_{direction}.png", transparent_color=(128, 128, 128), surface=False)
                self.rat_assets_textures[sex][direction] = texture
                # Cache size to avoid get_image_size() calls in draw loop
                self.rat_image_sizes[sex][direction] = texture.size
        
        for n in range(5):
            self.bomb_assets[n] = self.render_engine.load_image(f"Rat/BMP_BOMB{n}.png", transparent_color=(128, 128, 128))
        self.assets = {}
        for file in os.listdir("assets/Rat"):
            if file.endswith(".png"):
                self.assets[file[:-4]] = self.render_engine.load_image(f"Rat/{file}", transparent_color=(128, 128, 128))
        
        # Pre-generate blood stain textures pool (optimization)
        print("Pre-generating blood stain pool...")
        self.blood_stain_textures = []
        for _ in range(10):
            blood_surface = self.render_engine.generate_blood_surface()
            blood_texture = self.render_engine.draw_blood_surface(blood_surface, (0, 0))
            if blood_texture:
                self.blood_stain_textures.append(blood_texture)
        
        # Blood layer sprites (instead of regenerating background)
        self.blood_layer_sprites = []
        


    # ==================== RENDERING ====================

    def draw_maze(self):
        if self.background_texture is None:
            print("Generating background texture")
            self.regenerate_background()
        self.render_engine.draw_background(self.background_texture)
        
        # Draw blood layer as sprites (optimized - no background regeneration)
        self.draw_blood_layer()
    
    def draw_blood_layer(self):
        """Draw all blood stains as sprites overlay (optimized)"""
        for blood_texture, x, y in self.blood_layer_sprites:
            self.render_engine.draw_image(x, y, blood_texture, tag="blood")
    
    def regenerate_background(self):
        """Generate or regenerate the background texture (static - no blood stains)"""
        texture_tiles = []
        for y, row in enumerate(self.map.matrix):
            for x, cell in enumerate(row):
                variant = x*y % 4
                tile = self.grasses[variant] if cell else self.tunnel
                texture_tiles.append((tile, x*self.cell_size, y*self.cell_size))
        
        # Blood stains now handled separately as overlay layer
        self.background_texture = self.render_engine.create_texture(texture_tiles)
    
    def add_blood_stain(self, position):
        """Add a blood stain as sprite overlay (optimized - no background regeneration)"""
        import random
        
        # Pick random blood texture from pre-generated pool
        if not self.blood_stain_textures:
            return
        
        blood_texture = random.choice(self.blood_stain_textures)
        x = position[0] * self.cell_size
        y = position[1] * self.cell_size
        
        # Add to blood layer sprites instead of regenerating background
        self.blood_layer_sprites.append((blood_texture, x, y))
        
    def scroll_cursor(self, x=0, y=0):
        if self.pointer[0] + x > self.map.width or self.pointer[1] + y > self.map.height:
            return
        
        self.pointer = (
            max(1, min(self.map.width-2, self.pointer[0] + x)),
            max(1, min(self.map.height-2, self.pointer[1] + y))
        )
        self.render_engine.scroll_view(self.pointer)