import os
from flask_mail import Mail, Message
from flask import current_app

mail = Mail()

def init_mail(app):
    # Your email infrastructure configuration
    app.config['MAIL_SERVER'] = os.environ.get('MAIL_SERVER', 'localhost')
    app.config['MAIL_PORT'] = int(os.environ.get('MAIL_PORT', 25))
    app.config['MAIL_USE_TLS'] = os.environ.get('MAIL_USE_TLS', 'false').lower() == 'true'
    app.config['MAIL_USE_SSL'] = os.environ.get('MAIL_USE_SSL', 'false').lower() == 'true'

    # Only set username/password if they are provided and not empty
    username = os.environ.get('MAIL_USERNAME', '')
    password = os.environ.get('MAIL_PASSWORD', '')

    # Flask-Mail requires both username AND password, or neither
    if username and password:
        app.config['MAIL_USERNAME'] = username
        app.config['MAIL_PASSWORD'] = password
    else:
        # Explicitly set to None to avoid authentication
        app.config['MAIL_USERNAME'] = None
        app.config['MAIL_PASSWORD'] = None

    app.config['MAIL_DEFAULT_SENDER'] = os.environ.get('MAIL_DEFAULT_SENDER', 'LawBot <lawbot@apollomx.com>')

    # Production settings
    app.config['MAIL_DEBUG'] = False
    app.config['MAIL_SUPPRESS_SEND'] = False

    mail.init_app(app)

    # Simple startup confirmation
    print(f"📧 Email configured: {app.config['MAIL_SERVER']}:{app.config['MAIL_PORT']}")

def send_invitation_email(email, invitation_url, company_name):
    """Send invitation email to new user"""
    try:
        msg = Message(
            subject=f'Invitation to join {company_name} on EPOLaw',
            recipients=[email],
            sender='EPOLaw Team <invitations@epolaw.ai>'  # Custom sender for invitations
        )

        msg.body = f"""
You have been invited to join {company_name} on EPOLaw.

Please click the link below to accept your invitation and create your account:

{invitation_url}

This invitation will expire in 7 days.

If you did not expect this invitation, please ignore this email.

Best regards,
The EPOLaw Team
"""

        msg.html = f"""
<html>
<body style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
    <div style="background-color: #f8f9fa; padding: 20px; border-radius: 10px;">
        <h2 style="color: #333;">Welcome to EPOLaw!</h2>
        <p>You have been invited to join <strong>{company_name}</strong> on EPOLaw.</p>
        <p>Please click the button below to accept your invitation and create your account:</p>
        <div style="text-align: center; margin: 30px 0;">
            <a href="{invitation_url}" style="background-color: #007bff; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; display: inline-block;">
                Accept Invitation
            </a>
        </div>
        <p>Or copy and paste this link into your browser:</p>
        <p style="word-break: break-all; color: #007bff;">{invitation_url}</p>
        <p style="color: #666; font-style: italic;">This invitation will expire in 7 days.</p>
        <hr style="border: 1px solid #eee;">
        <p style="color: #999; font-size: 12px;">If you did not expect this invitation, please ignore this email.</p>
    </div>
</body>
</html>
"""

        mail.send(msg)
        current_app.logger.info(f"Invitation email sent successfully to {email}")
        return True

    except Exception as e:
        current_app.logger.error(f"Failed to send invitation email to {email}: {str(e)}")
        return False

def send_password_reset_email(email, reset_url):
    """Send password reset email"""
    try:
        msg = Message(
            subject='Password Reset Request - EPOLaw',
            recipients=[email],
            sender='EPOLaw Team <support@epolaw.ai>'  # Different sender for password resets
        )

        msg.body = f"""
You have requested to reset your password for EPOLaw.

Please click the link below to reset your password:

{reset_url}

This link will expire in 24 hours.

If you did not request this password reset, please ignore this email.

Best regards,
The EPOLaw Team
"""

        msg.html = f"""
<html>
<body style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
    <div style="background-color: #f8f9fa; padding: 20px; border-radius: 10px;">
        <h2 style="color: #333;">Password Reset Request</h2>
        <p>You have requested to reset your password for EPOLaw.</p>
        <div style="text-align: center; margin: 30px 0;">
            <a href="{reset_url}" style="background-color: #dc3545; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; display: inline-block;">
                Reset Password
            </a>
        </div>
        <p>Or copy and paste this link into your browser:</p>
        <p style="word-break: break-all; color: #007bff;">{reset_url}</p>
        <p style="color: #666; font-style: italic;">This link will expire in 24 hours.</p>
        <hr style="border: 1px solid #eee;">
        <p style="color: #999; font-size: 12px;">If you did not request this password reset, please ignore this email.</p>
    </div>
</body>
</html>
"""

        mail.send(msg)
        current_app.logger.info(f"Password reset email sent successfully to {email}")
        return True

    except Exception as e:
        current_app.logger.error(f"Failed to send password reset email to {email}: {str(e)}")
        return False

def send_registration_notification(user):
    """Send registration notification to admin with user details"""
    try:
        # Get admin email from environment or use default
        admin_email = os.environ.get('ADMIN_EMAIL', 'admin@epolaw.ai')

        msg = Message(
            subject=f'New User Registration - {user.first_name} {user.last_name}',
            recipients=[admin_email],
            sender='EPOLaw Notifications <notifications@epolaw.ai>'
        )

        msg.body = f"""
New User Registration on EPOLaw

User Details:
-------------
Name: {user.first_name} {user.last_name}
Email: {user.email}
Phone Number: {user.phone_number}
Registration Date: {user.created_at.strftime('%B %d, %Y at %I:%M %p UTC') if user.created_at else 'N/A'}

This user has successfully registered for EPOLaw.

---
EPOLaw Admin Notifications
"""

        msg.html = f"""
<html>
<body style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
    <div style="background-color: #f8f9fa; padding: 20px; border-radius: 10px;">
        <h2 style="color: #007bff;">New User Registration</h2>
        <p>A new user has registered on EPOLaw:</p>

        <div style="background-color: white; padding: 20px; border-radius: 5px; margin: 20px 0;">
            <h3 style="color: #333; margin-top: 0;">User Details</h3>
            <table style="width: 100%; border-collapse: collapse;">
                <tr style="border-bottom: 1px solid #eee;">
                    <td style="padding: 10px 0; font-weight: bold; color: #666;">Name:</td>
                    <td style="padding: 10px 0;">{user.first_name} {user.last_name}</td>
                </tr>
                <tr style="border-bottom: 1px solid #eee;">
                    <td style="padding: 10px 0; font-weight: bold; color: #666;">Email:</td>
                    <td style="padding: 10px 0;"><a href="mailto:{user.email}">{user.email}</a></td>
                </tr>
                <tr style="border-bottom: 1px solid #eee;">
                    <td style="padding: 10px 0; font-weight: bold; color: #666;">Phone Number:</td>
                    <td style="padding: 10px 0;"><a href="tel:{user.phone_number}">{user.phone_number}</a></td>
                </tr>
                <tr>
                    <td style="padding: 10px 0; font-weight: bold; color: #666;">Registration Date:</td>
                    <td style="padding: 10px 0;">{user.created_at.strftime('%B %d, %Y at %I:%M %p UTC') if user.created_at else 'N/A'}</td>
                </tr>
            </table>
        </div>

        <hr style="border: 1px solid #eee; margin: 20px 0;">
        <p style="color: #999; font-size: 12px; text-align: center;">
            EPOLaw Admin Notifications
        </p>
    </div>
</body>
</html>
"""

        mail.send(msg)
        current_app.logger.info(f"Registration notification sent to admin for user: {user.email}")
        return True

    except Exception as e:
        current_app.logger.error(f"Failed to send registration notification for {user.email}: {str(e)}")
        return False
