"""
System Module Admin
"""
from django.contrib import admin
from igny8_core.admin.base import AccountAdminMixin
from .models import AIPrompt, IntegrationSettings, AuthorProfile, Strategy

# Import settings admin
from .settings_admin import (
    SystemSettingsAdmin, AccountSettingsAdmin, UserSettingsAdmin,
    ModuleSettingsAdmin, AISettingsAdmin
)

try:
    from .models import SystemLog, SystemStatus
    
    @admin.register(SystemLog)
    class SystemLogAdmin(AccountAdminMixin, admin.ModelAdmin):
        list_display = ['id', 'account', 'module', 'level', 'action', 'message', 'created_at']
        list_filter = ['module', 'level', 'created_at', 'account']
        search_fields = ['message', 'action']
        readonly_fields = ['created_at', 'updated_at']
        date_hierarchy = 'created_at'


    @admin.register(SystemStatus)
    class SystemStatusAdmin(AccountAdminMixin, admin.ModelAdmin):
        list_display = ['component', 'account', 'status', 'message', 'last_check']
        list_filter = ['status', 'component', 'account']
        search_fields = ['component', 'message']
        readonly_fields = ['last_check']
except ImportError:
    pass


@admin.register(AIPrompt)
class AIPromptAdmin(AccountAdminMixin, admin.ModelAdmin):
    list_display = ['id', 'prompt_type', 'account', 'is_active', 'updated_at']
    list_filter = ['prompt_type', 'is_active', 'account']
    search_fields = ['prompt_type']
    readonly_fields = ['created_at', 'updated_at', 'default_prompt']
    
    fieldsets = (
        ('Basic Info', {
            'fields': ('account', 'prompt_type', 'is_active')
        }),
        ('Prompt Content', {
            'fields': ('prompt_value', 'default_prompt')
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at')
        }),
    )
    
    def get_account_display(self, obj):
        """Safely get account name"""
        try:
            account = getattr(obj, 'account', None)
            return account.name if account else '-'
        except:
            return '-'
    get_account_display.short_description = 'Account'


@admin.register(IntegrationSettings)
class IntegrationSettingsAdmin(AccountAdminMixin, admin.ModelAdmin):
    list_display = ['id', 'integration_type', 'account', 'is_active', 'updated_at']
    list_filter = ['integration_type', 'is_active', 'account']
    search_fields = ['integration_type']
    readonly_fields = ['created_at', 'updated_at']
    
    fieldsets = (
        ('Basic Info', {
            'fields': ('account', 'integration_type', 'is_active')
        }),
        ('Configuration', {
            'fields': ('config',),
            'description': 'JSON configuration containing API keys and settings. Example: {"apiKey": "sk-...", "model": "gpt-4.1", "enabled": true}'
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at')
        }),
    )
    
    def get_readonly_fields(self, request, obj=None):
        """Make config readonly when viewing to prevent accidental exposure"""
        if obj:  # Editing existing object
            return self.readonly_fields + ['config']
        return self.readonly_fields
    
    def get_account_display(self, obj):
        """Safely get account name"""
        try:
            account = getattr(obj, 'account', None)
            return account.name if account else '-'
        except:
            return '-'
    get_account_display.short_description = 'Account'


@admin.register(AuthorProfile)
class AuthorProfileAdmin(AccountAdminMixin, admin.ModelAdmin):
    list_display = ['name', 'account', 'tone', 'language', 'is_active', 'created_at']
    list_filter = ['is_active', 'tone', 'language', 'account']
    search_fields = ['name', 'description', 'tone']
    readonly_fields = ['created_at', 'updated_at']
    
    fieldsets = (
        ('Basic Info', {
            'fields': ('account', 'name', 'description', 'is_active')
        }),
        ('Writing Style', {
            'fields': ('tone', 'language', 'structure_template')
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at')
        }),
    )
    
    def get_account_display(self, obj):
        """Safely get account name"""
        try:
            account = getattr(obj, 'account', None)
            return account.name if account else '-'
        except:
            return '-'
    get_account_display.short_description = 'Account'


@admin.register(Strategy)
class StrategyAdmin(AccountAdminMixin, admin.ModelAdmin):
    list_display = ['name', 'account', 'sector', 'is_active', 'created_at']
    list_filter = ['is_active', 'account']
    search_fields = ['name', 'description']
    readonly_fields = ['created_at', 'updated_at']
    
    fieldsets = (
        ('Basic Info', {
            'fields': ('account', 'name', 'description', 'sector', 'is_active')
        }),
        ('Strategy Configuration', {
            'fields': ('prompt_types', 'section_logic')
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at')
        }),
    )
    
    def get_account_display(self, obj):
        """Safely get account name"""
        try:
            account = getattr(obj, 'account', None)
            return account.name if account else '-'
        except:
            return '-'
    get_account_display.short_description = 'Account'
    
    def get_sector_display(self, obj):
        """Safely get sector name"""
        try:
            return obj.sector.name if obj.sector else 'Global'
        except:
            return 'Global'
    get_sector_display.short_description = 'Sector'
