from django import template
import os

register = template.Library()
from django.conf import settings

@register.simple_tag
def color_images_url(default_image, color_name, sku):
    """
    Returns color-specific image URLs from the color-specific folder structure.
    Structure expected:
    static/shop/images/products/
    ├── {sku}/
    │   ├── default.jpg  (or any supported extension)
    │   └── {color_name}/
    │       └── image.jpg (or any supported extension)
    """
    # List of supported image extensions
    supported_extensions = ['.png.avif', '.jpg', '.jpeg', '.png', '.gif', '.webp', '.avif']

    # Base path for products
    base_path = f'/static/shop/images/products/{sku}/'
    physical_base_path = os.path.join(settings.BASE_DIR, 'shop', 'static', 'shop', 'images', 'products', sku)

    if color_name:
        # Generate color folder name (sanitize the color name)
        color_folder = generate_color_folder_name(color_name)

        # Check color-specific folder
        color_path = os.path.join(physical_base_path, color_folder)
        if os.path.exists(color_path):
            # Get all images from color folder
            files = [f for f in os.listdir(color_path)
                    if any(f.lower().endswith(ext) for ext in supported_extensions)]

            if files:
                # Sort files by specific prefix rules
                files.sort(key=lambda x: (
                    1 if '-B_' in x else
                    2 if '-S_' in x else
                    0
                ))
                return [f'{base_path}{color_folder}/{file}' for file in files]

    # If no color-specific image found, look for default image in product folder
    if os.path.exists(physical_base_path):
        files = [f for f in os.listdir(physical_base_path)
                if os.path.isfile(os.path.join(physical_base_path, f)) and
                any(f.lower().endswith(ext) for ext in supported_extensions)]
        if files:
            files.sort(key=lambda x: (
                1 if '-B_' in x else
                2 if '-S_' in x else
                0
            ))
            return [f'{base_path}{file}' for file in files]

    # If nothing found, return list with default image
    return [default_image]

def generate_color_folder_name(color_name):
    """
    Generates a folder-friendly name from a color name
    Example: "Noir / Gris Foncé Chiné" becomes "noir-gris-fonce-chine"
    """
    import unicodedata
    import re

    # Convert to lowercase and replace accents
    value = color_name.lower()
    value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')

    # Replace slashes and spaces with hyphens
    value = re.sub(r'[/\s]+', '-', value)

    # Remove any remaining non-alphanumeric characters except hyphens
    value = re.sub(r'[^\w-]', '', value)

    return value
