"""
Custom AdminSite for IGNY8 to organize models into proper groups
"""
from django.contrib import admin
from django.contrib.admin.apps import AdminConfig
from django.apps import apps


class Igny8AdminSite(admin.AdminSite):
    """
    Custom AdminSite that organizes models into the planned groups:
    1. Billing & Tenancy
    2. Sites & Users
    3. Global Reference Data
    4. Planner
    5. Writer Module
    6. Thinker Module
    7. System Configuration
    """
    site_header = 'IGNY8 Administration'
    site_title = 'IGNY8 Admin'
    index_title = 'IGNY8 Administration'

    def get_app_list(self, request):
        """
        Customize the app list to organize models into proper groups
        """
        # Get the default app list
        app_dict = self._build_app_dict(request)
        
        # Define our custom groups with their models (using object_name)
        custom_groups = {
            'Billing & Tenancy': {
                'models': [
                    ('igny8_core_auth', 'Plan'),
                    ('igny8_core_auth', 'Account'),
                    ('igny8_core_auth', 'Subscription'),
                    ('billing', 'CreditTransaction'),
                    ('billing', 'CreditUsageLog'),
                ],
            },
            'Sites & Users': {
                'models': [
                    ('igny8_core_auth', 'Site'),
                    ('igny8_core_auth', 'User'),
                    ('igny8_core_auth', 'SiteUserAccess'),
                    ('igny8_core_auth', 'PasswordResetToken'),
                ],
            },
            'Global Reference Data': {
                'models': [
                    ('igny8_core_auth', 'Industry'),
                    ('igny8_core_auth', 'IndustrySector'),
                    ('igny8_core_auth', 'SeedKeyword'),
                ],
            },
            'Planner': {
                'models': [
                    ('planner', 'Keywords'),
                    ('planner', 'Clusters'),
                    ('planner', 'ContentIdeas'),
                ],
            },
            'Writer Module': {
                'models': [
                    ('writer', 'Tasks'),
                    ('writer', 'Content'),
                    ('writer', 'Images'),
                ],
            },
            'Thinker Module': {
                'models': [
                    ('system', 'AIPrompt'),
                    ('system', 'AuthorProfile'),
                    ('system', 'Strategy'),
                ],
            },
            'System Configuration': {
                'models': [
                    ('system', 'IntegrationSettings'),
                    ('system', 'SystemLog'),
                    ('system', 'SystemStatus'),
                    ('system', 'SystemSettings'),
                    ('system', 'AccountSettings'),
                    ('system', 'UserSettings'),
                    ('system', 'ModuleSettings'),
                    ('system', 'AISettings'),
                ],
            },
        }
        
        # Build the custom app list
        app_list = []
        
        for group_name, group_config in custom_groups.items():
            group_models = []
            
            for app_label, model_name in group_config['models']:
                # Find the model in app_dict
                if app_label in app_dict:
                    app_data = app_dict[app_label]
                    # Look for the model in the app's models
                    for model in app_data.get('models', []):
                        if model['object_name'] == model_name:
                            group_models.append(model)
                            break
            
            # Only add the group if it has models
            if group_models:
                app_list.append({
                    'name': group_name,
                    'app_label': group_name.lower().replace(' ', '_').replace('&', ''),
                    'app_url': None,
                    'has_module_perms': True,
                    'models': group_models,
                })
        
        # Sort the app list by our custom order
        order = [
            'Billing & Tenancy',
            'Sites & Users',
            'Global Reference Data',
            'Planner',
            'Writer Module',
            'Thinker Module',
            'System Configuration',
        ]
        
        app_list.sort(key=lambda x: order.index(x['name']) if x['name'] in order else 999)
        
        return app_list



