import secrets
import string
from django.core.mail import send_mail, EmailMessage
from django.conf import settings
from django.utils import timezone
from datetime import timedelta
from .models import AppSettings
from ErrorLogs.utils import log_error


def generate_temp_password(length=16):
    """Generate a secure random temporary password"""
    alphabet = string.ascii_letters + string.digits + "!@#$%^&*"
    password = ''.join(secrets.choice(alphabet) for i in range(length))
    return password


def send_welcome_email(user_email, user_name, temp_password, login_url=None):
    """
    Send welcome email with temporary password to new employee
    
    Args:
        user_email: Employee's email address
        user_name: Employee's full name
        temp_password: Temporary password to send
        login_url: URL for login page (optional)
    """
    try:
        from django.conf import settings as django_settings
        app_settings = AppSettings.get_settings()
        
        # Check if SMTP is enabled
        if not app_settings.smtp_enabled:
            log_error('send_welcome_email', Exception('SMTP is not enabled'))
            return False
        
        # Configure Django email settings from AppSettings
        django_settings.EMAIL_HOST = app_settings.smtp_host
        django_settings.EMAIL_PORT = app_settings.smtp_port
        django_settings.EMAIL_USE_TLS = app_settings.smtp_use_tls
        django_settings.EMAIL_USE_SSL = app_settings.smtp_use_ssl
        django_settings.EMAIL_HOST_USER = app_settings.smtp_username
        django_settings.EMAIL_HOST_PASSWORD = app_settings.smtp_password
        django_settings.DEFAULT_FROM_EMAIL = app_settings.smtp_from_email or app_settings.smtp_username
        
        # Build login URL if not provided
        if not login_url:
            # Try to get from request or use default
            login_url = getattr(django_settings, 'LOGIN_URL', 'http://localhost:3000/login')
        
        # Calculate expiration time
        expires_hours = app_settings.temp_password_expires_hours
        expiration_time = timezone.now() + timedelta(hours=expires_hours)
        
        # Email subject
        subject = f'Welcome to {app_settings.smtp_from_name or "TimeTracker"} - Your Account Credentials'
        
        # Email body (plain text)
        message = f"""Hello {user_name},

Your account has been created. Please use the following temporary password to log in:

Temporary Password: {temp_password}

Login URL: {login_url}

IMPORTANT: You must change this password on your first login for security reasons.
This temporary password will expire in {expires_hours} hours ({expiration_time.strftime('%Y-%m-%d %H:%M')}).

If you did not expect this email, please contact your administrator immediately.

Best regards,
{app_settings.smtp_from_name or 'TimeTracker'} Team"""
        
        # Send email
        from_email = f"{app_settings.smtp_from_name or 'TimeTracker'} <{app_settings.smtp_from_email or app_settings.smtp_username}>"
        
        send_mail(
            subject=subject,
            message=message,
            from_email=from_email,
            recipient_list=[user_email],
            fail_silently=False,
        )
        
        return True
        
    except Exception as e:
        log_error('send_welcome_email', e)
        return False

