
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
import requests
from urllib.parse import urlparse


class MpesaHealthCheck:
    """Health check utility for M-Pesa configuration"""
    
    @staticmethod
    def check_mpesa_settings():
        """Check M-Pesa configuration for completeness and validity"""
        errors = []
        warnings = []
        
        # Check required settings
        required_settings = [
            'MPESA_CONSUMER_KEY',
            'MPESA_CONSUMER_SECRET', 
            'MPESA_BUSINESS_SHORT_CODE',
            'MPESA_PASSKEY',
            'MPESA_ENVIRONMENT'
        ]
        
        for setting_name in required_settings:
            value = getattr(settings, setting_name, '')
            if not value:
                errors.append(f"Missing required setting: {setting_name}")
        
        # Check environment value
        mpesa_env = getattr(settings, 'MPESA_ENVIRONMENT', 'sandbox')
        if mpesa_env not in ['sandbox', 'production']:
            errors.append(f"MPESA_ENVIRONMENT must be 'sandbox' or 'production', got: {mpesa_env}")
        
        # Check callback URLs
        callback_base = getattr(settings, 'MPESA_CALLBACK_BASE_URL', '')
        if callback_base:
            parsed = urlparse(callback_base)
            if not parsed.scheme:
                errors.append("MPESA_CALLBACK_BASE_URL must include protocol (https://)")
            elif parsed.scheme != 'https' and mpesa_env == 'production':
                errors.append("Production M-Pesa requires HTTPS callback URLs")
            elif parsed.netloc in ['localhost', '127.0.0.1', 'your-domain.com']:
                warnings.append("Callback URL appears to be a placeholder or localhost")
        else:
            errors.append("MPESA_CALLBACK_BASE_URL is required")
        
        # Check ALLOWED_HOSTS and CSRF settings
        if callback_base:
            domain = urlparse(callback_base).netloc
            allowed_hosts = getattr(settings, 'ALLOWED_HOSTS', [])
            if domain not in allowed_hosts and '*' not in allowed_hosts:
                warnings.append(f"Domain {domain} not in ALLOWED_HOSTS - callbacks may be blocked")
            
            csrf_origins = getattr(settings, 'CSRF_TRUSTED_ORIGINS', [])
            callback_origin = f"https://{domain}"
            if callback_origin not in csrf_origins and mpesa_env == 'production':
                warnings.append(f"Origin {callback_origin} not in CSRF_TRUSTED_ORIGINS - callbacks may be blocked")
        
        # Check SystemSettings vs Django settings alignment
        try:
            from settings.models import SystemSettings
            db_settings = SystemSettings.get_mpesa_settings()
            
            # Compare key settings
            django_consumer_key = getattr(settings, 'MPESA_CONSUMER_KEY', '')
            db_consumer_key = db_settings.get('consumer_key', '')
            
            if django_consumer_key and db_consumer_key and django_consumer_key != db_consumer_key:
                warnings.append("MPESA_CONSUMER_KEY in Django settings differs from SystemSettings")
            
            django_env = getattr(settings, 'MPESA_ENVIRONMENT', 'sandbox')
            db_env = db_settings.get('environment', 'sandbox')
            
            if django_env != db_env:
                warnings.append(f"Environment mismatch: Django='{django_env}', DB='{db_env}'")
                
        except Exception as e:
            warnings.append(f"Could not check SystemSettings: {e}")
        
        return {
            'errors': errors,
            'warnings': warnings,
            'is_healthy': len(errors) == 0
        }
    
    @staticmethod
    def get_effective_mpesa_config():
        """Get the effective M-Pesa configuration (Django settings take precedence)"""
        from settings.models import SystemSettings
        
        # Start with DB settings
        try:
            db_settings = SystemSettings.get_mpesa_settings()
        except:
            db_settings = {}
        
        # Override with Django settings (environment variables)
        config = {
            'consumer_key': getattr(settings, 'MPESA_CONSUMER_KEY', '') or db_settings.get('consumer_key', ''),
            'consumer_secret': getattr(settings, 'MPESA_CONSUMER_SECRET', '') or db_settings.get('consumer_secret', ''),
            'business_short_code': getattr(settings, 'MPESA_BUSINESS_SHORT_CODE', '') or db_settings.get('business_short_code', ''),
            'passkey': getattr(settings, 'MPESA_PASSKEY', '') or db_settings.get('passkey', ''),
            'environment': getattr(settings, 'MPESA_ENVIRONMENT', 'sandbox'),
            'stk_callback_url': getattr(settings, 'MPESA_STK_CALLBACK_URL', ''),
            'c2b_validation_url': getattr(settings, 'MPESA_C2B_VALIDATION_URL', ''),
            'c2b_confirmation_url': getattr(settings, 'MPESA_C2B_CONFIRMATION_URL', ''),
        }
        
        return config
