# -*- coding: utf-8 -*-
"""
Analytics App Configuration
===========================

Django app configuration for the Adtlas Analytics module.
This file defines the app configuration, metadata, and initialization settings.

The Analytics app is responsible for:
- Collecting and processing advertising performance data
- Integrating with external analytics providers (SFR, Bouygues)
- Generating reports and dashboards
- Tracking VAST responses and impressions
- Providing real-time analytics capabilities

App Features:
- Real-time data collection
- Multi-provider analytics integration
- Custom report generation
- Performance metrics calculation
- Data visualization support
- Export capabilities
- Predictive analytics

Dependencies:
- Django REST Framework for API endpoints
- Celery for background data processing
- Redis for caching analytics data
- PostgreSQL for data storage
- External analytics APIs (SFR, Bouygues)

Author: Adtlas Development Team
Version: 1.0.0
Created: 2024
"""

from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _


class AnalyticsConfig(AppConfig):
    """
    Configuration class for the Analytics app.
    
    This class defines the app configuration including:
    - App name and label
    - Default auto field type
    - Verbose name for admin interface
    - Signal handlers registration
    - App initialization logic
    
    Attributes:
        default_auto_field (str): Default primary key field type
        name (str): Full Python path to the app
        label (str): Short name for the app
        verbose_name (str): Human-readable name for the app
    """
    
    # Default primary key field type for models in this app
    default_auto_field = 'django.db.models.BigAutoField'
    
    # Full Python path to the application
    name = 'apps.analytics'
    
    # Short name for the app (used internally by Django)
    label = 'analytics'
    
    # Human-readable name for the app (displayed in admin)
    verbose_name = _('Analytics & Reporting')
    
    def ready(self):
        """
        Perform initialization when Django starts.
        
        This method is called when the app is ready and Django has finished
        loading all apps. It's used to:
        - Import and register signal handlers
        - Initialize background tasks
        - Set up analytics data collectors
        - Configure external API connections
        - Register custom admin actions
        
        Note:
            This method should not perform database operations as the
            database might not be ready yet during startup.
        """
        try:
            # Import signal handlers to register them
            from . import signals  # noqa: F401
            
            # Import and register analytics tasks
            from . import tasks  # noqa: F401
            
            # Initialize analytics services
            self._initialize_analytics_services()
            
        except ImportError as e:
            # Handle import errors gracefully during development
            import logging
            logger = logging.getLogger(__name__)
            logger.warning(f"Analytics app initialization warning: {e}")
    
    def _initialize_analytics_services(self):
        """
        Initialize analytics services and connections.
        
        This private method sets up:
        - External analytics API connections
        - Data collection services
        - Real-time processing pipelines
        - Cache warming for frequently accessed data
        
        Note:
            This method is called during app initialization and should
            not perform heavy operations that could slow down startup.
        """
        try:
            # Initialize analytics service connections
            from .services import AnalyticsService
            
            # Warm up connection pools (non-blocking)
            analytics_service = AnalyticsService()
            analytics_service.initialize_connections()
            
            # Register periodic tasks for data collection
            self._register_periodic_tasks()
            
        except Exception as e:
            # Log initialization errors but don't fail startup
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"Analytics service initialization error: {e}")
    
    def _register_periodic_tasks(self):
        """
        Register periodic Celery tasks for analytics data collection.
        
        This method sets up recurring tasks for:
        - Collecting data from external analytics providers
        - Processing VAST response data
        - Generating daily/weekly/monthly reports
        - Cleaning up old analytics data
        - Updating performance metrics
        
        Note:
            Tasks are registered with Celery Beat for scheduled execution.
        """
        try:
            from django_celery_beat.models import PeriodicTask, IntervalSchedule
            from django.db import transaction
            
            # This will be implemented when Celery tasks are created
            # For now, we just log that the registration would happen here
            import logging
            logger = logging.getLogger(__name__)
            logger.info("Analytics periodic tasks registration placeholder")
            
        except Exception as e:
            # Handle errors gracefully
            import logging
            logger = logging.getLogger(__name__)
            logger.warning(f"Periodic task registration warning: {e}")