import importlib
from django.apps import apps
from .registry import sync_registry
from collections import defaultdict

def build_serializer_class(model_name):

    # Remove the 's' character at the end if present
    if model_name.endswith('s') and not model_name.endswith('ss'):
        model_name = model_name[:-1]

    # Capitalize words separated by a dash
    words = model_name.split('-')
    capitalized_words = [word[0].upper() + word[1:] for word in words]
    transformed_string = ''.join(capitalized_words)

    # Add 'Serializer' at the end
    transformed_string += 'Serializer'

    # Try to find serializer in current directory first
    try:
        module = importlib.import_module('api.serializers')
        return getattr(module, transformed_string)
    except (ImportError, AttributeError):
        module = importlib.import_module('.serializers', package=__package__)
        return getattr(module, transformed_string)

def get_serializer(instance, model_name):
    serializer = build_serializer_class(model_name)
    return serializer(instance)

def get_data(model_name, model_id):
    model = sync_registry.get_model(model_name)
    # model = apps.get_model(app_label=app_label, model_name=model_name)
    return model.objects.get(id=model_id)

def get_serialized_data(model_name, model_id):
    # print(f'model_name = {model_name}')
    model = sync_registry.get_model(model_name)
    instance = model.objects.get(id=model_id)
    serializer_class = build_serializer_class(model_name)
    serializer = serializer_class(instance)
    return serializer.data

class HierarchyOrganizer:
    def __init__(self):
        self.levels = []  # List of dictionaries, each representing a level
        self.item_levels = {}  # Keep track of items and their levels: (model_name, id) -> level

    def add_item(self, model_name, item_data, level):
        """
        Add an item to a specific level, ensuring it's at the highest level if already exists
        """
        item_key = (model_name, item_data['model_id'])

        # If item exists at a lower level, remove it
        existing_level = self.item_levels.get(item_key)
        if existing_level is not None:
            if existing_level < level:
                # Keep the lower level (deeper in hierarchy)
                return
            # Remove from existing level
            self.levels[existing_level][model_name] = [
                item for item in self.levels[existing_level].get(model_name, [])
                if item['model_id'] != item_data['model_id']
            ]

        # Ensure we have enough levels
        while len(self.levels) <= level:
            self.levels.append(defaultdict(list))

        # Add item to the appropriate level
        if model_name not in self.levels[level]:
            self.levels[level][model_name] = []
        self.levels[level][model_name].append(item_data)
        self.item_levels[item_key] = level

    def get_organized_data(self):
        """
        Return the organized levels, cleaning up empty models/levels
        """
        # Clean up empty models and levels
        cleaned_levels = []
        for level_dict in self.levels:
            cleaned_dict = {k: v for k, v in level_dict.items() if v}
            if cleaned_dict:
                cleaned_levels.append(cleaned_dict)
        return cleaned_levels
