"""
Import/Export resource class generation.

Auto-generates ModelResource classes for import/export functionality.
"""

import logging
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ...config import AdminConfig

logger = logging.getLogger(__name__)


def generate_resource_class(config: 'AdminConfig'):
    """
    Auto-generate a ModelResource class for import/export.

    Uses ResourceConfig if provided, otherwise generates basic Resource.

    Args:
        config: AdminConfig instance

    Returns:
        Generated ModelResource class
    """
    from import_export import resources

    target_model = config.model
    resource_config = config.resource_config

    # Determine fields to include
    if resource_config and resource_config.fields:
        # Use explicitly specified fields
        model_fields = resource_config.fields
    else:
        # Auto-detect fields from model
        model_fields = []
        for field in target_model._meta.get_fields():
            # Skip relations and auto fields that shouldn't be imported
            if field.concrete and not field.many_to_many:
                # Skip password fields for security
                if 'password' not in field.name.lower():
                    model_fields.append(field.name)

    # Apply exclusions if specified
    if resource_config and resource_config.exclude:
        model_fields = [f for f in model_fields if f not in resource_config.exclude]

    # Build Meta attributes
    meta_attrs = {
        'model': target_model,
        'fields': tuple(model_fields),
    }

    # Add ResourceConfig settings
    if resource_config:
        meta_attrs['import_id_fields'] = resource_config.import_id_fields
        meta_attrs['skip_unchanged'] = resource_config.skip_unchanged
        meta_attrs['report_skipped'] = resource_config.report_skipped
        meta_attrs['use_transactions'] = resource_config.use_transactions

        if resource_config.export_order:
            meta_attrs['export_order'] = tuple(resource_config.export_order)
    else:
        # Default settings
        meta_attrs['import_id_fields'] = ['id'] if 'id' in model_fields else []
        meta_attrs['skip_unchanged'] = True
        meta_attrs['report_skipped'] = True

    # Create Meta class
    ResourceMeta = type('Meta', (), meta_attrs)

    # Build Resource class attributes (methods + Meta)
    resource_attrs = {'Meta': ResourceMeta}

    # Add hooks from ResourceConfig
    if resource_config:
        # before_import hook
        if resource_config.before_import:
            hook = resource_config.get_callable('before_import')
            if hook:
                resource_attrs['before_import'] = hook

        # after_import hook
        if resource_config.after_import:
            hook = resource_config.get_callable('after_import')
            if hook:
                resource_attrs['after_import'] = hook

        # before_import_row hook
        if resource_config.before_import_row:
            hook = resource_config.get_callable('before_import_row')
            if hook:
                resource_attrs['before_import_row'] = hook

        # after_import_row hook
        if resource_config.after_import_row:
            hook = resource_config.get_callable('after_import_row')
            if hook:
                resource_attrs['after_import_row'] = hook

    # Create Resource class
    AutoGeneratedResource = type(
        f'{target_model.__name__}Resource',
        (resources.ModelResource,),
        resource_attrs
    )

    return AutoGeneratedResource
