import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import logging
from datetime import datetime
from app.core.config import settings

logger = logging.getLogger("uvicorn.error")

DEFAULT_FROM_NAME = "Insurance Border"

def _print_console_fallback(to_email: str, subject: str, html_content: str, header_title: str) -> None:
    """Prints email content to the console for testing/debugging."""
    print("\n" + "="*80)
    print(f" [{header_title}] ")
    print(f" To:       {to_email}")
    print(f" Subject:  {subject}")
    print(f" Body:\n{html_content}")
    print("="*80 + "\n")

def _send_smtp(to_email: str, subject: str, html_content: str) -> bool:
    """Attempts sending email via SMTP. Returns True on success, False on failure."""
    try:
        msg = MIMEMultipart("alternative")
        msg["Subject"] = subject
        
        from_email = settings.SMTP_FROM_EMAIL or settings.SMTP_USERNAME
        from_name = settings.SMTP_FROM_NAME or DEFAULT_FROM_NAME
        msg["From"] = f"{from_name} <{from_email}>"
        msg["To"] = to_email

        part = MIMEText(html_content, "html")
        msg.attach(part)

        # Set up SMTP connection based on configuration
        if settings.SMTP_PORT == 465:
            server = smtplib.SMTP_SSL(settings.SMTP_HOST, settings.SMTP_PORT)
        else:
            server = smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT)
            server.ehlo()
            if settings.SMTP_PORT in (587, 25, 2525):
                server.starttls()
                server.ehlo()

        server.login(settings.SMTP_USERNAME, settings.SMTP_PASSWORD)
        server.sendmail(from_email, [to_email], msg.as_string())
        server.quit()
        logger.info(f"Email sent successfully to {to_email} via SMTP")
        return True
    except Exception as smtp_error:
        logger.warning(f"SMTP sending failed ({smtp_error}). Falling back to Pepipost API...")
        return False

def _send_pepipost(to_email: str, subject: str, html_content: str) -> bool:
    """Attempts sending email via Pepipost API. Returns True on success, False on failure."""
    try:
        import httpx
        
        # Determine Pepipost configuration
        pepipost_url = settings.PEPIPOST_API_URL or "https://api.pepipost.com/v5.1/mail/send"
        pepipost_key = settings.PEPIPOST_API_KEY or "1e2d806e2907cbe3388abe1ebba75135"
        
        # If using the default hardcoded key, we MUST use the verified sender domain
        if pepipost_key == "1e2d806e2907cbe3388abe1ebba75135":
            from_email = "alerts@employmentexchange.com"
            from_name = settings.PEPIPOST_FROM_NAME or settings.SMTP_FROM_NAME or DEFAULT_FROM_NAME
            logger.warning("Using fallback default Pepipost account with sender alerts@employmentexchange.com")
        else:
            from_email = settings.PEPIPOST_FROM_EMAIL or settings.SMTP_FROM_EMAIL or "noreply@insuranceborder.com"
            from_name = settings.PEPIPOST_FROM_NAME or settings.SMTP_FROM_NAME or DEFAULT_FROM_NAME
            logger.info("Using custom configured Pepipost credentials")

        payload = {
            "from": {"email": from_email, "name": from_name},
            "subject": subject,
            "content": [{"type": "html", "value": html_content}],
            "personalizations": [
                {
                    "to": [{"email": to_email}],
                    "attributes": {
                        "LEAD": to_email.split("@")[0],
                        "BAND": "Notification"
                    }
                }
            ]
        }
        
        headers = {
            "api_key": pepipost_key,
            "content-type": "application/json"
        }
        
        response = httpx.post(pepipost_url, json=payload, headers=headers)
        response.raise_for_status()
        logger.info(f"Email sent successfully to {to_email} via Pepipost API")
        return True
    except Exception as pepipost_error:
        logger.exception(f"Failed to send email to {to_email} via Pepipost API: {str(pepipost_error)}")
        return False

def send_email(to_email: str, subject: str, html_content: str) -> bool:
    """
    Low-level email helper. Sends emails using configured SMTP settings first.
    Falls back to Pepipost API (custom or default key) if SMTP fails.
    If settings are missing or testing mode is active, logs a warning and prints the email content to the console for testing.
    """
    if settings.TESTING:
        logger.info("Testing mode is active. Email bypassed.")
        _print_console_fallback(to_email, subject, html_content, "LOCAL EMAIL SERVICE PREVIEW")
        return True

    # 1. Try SMTP first if credentials are provided
    if settings.SMTP_HOST and settings.SMTP_USERNAME and settings.SMTP_PASSWORD:
        if _send_smtp(to_email, subject, html_content):
            return True

    # 2. Fallback to Pepipost API
    if _send_pepipost(to_email, subject, html_content):
        return True

    # Final fallback to console print
    _print_console_fallback(to_email, subject, html_content, "LOCAL EMAIL SERVICE PREVIEW - SEND ERROR FALLBACK")
    return False

def send_welcome_email(name: str, email: str) -> bool:
    """
    Sends a welcome email upon successful account registration.
    """
    from datetime import timezone
    current_time = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
    current_year = datetime.now(timezone.utc).year
    
    subject = "Welcome to Insurance Border – Account Created Successfully"
    
    html_content = f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome to Insurance Border</title>
    <style>
        body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f8fafc; color: #1e293b; margin: 0; padding: 0; }}
        .wrapper {{ width: 100%; background-color: #f8fafc; padding: 20px 0; }}
        .container {{ max-width: 600px; margin: 0 auto; background-color: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1); border: 1px solid #e2e8f0; }}
        .header {{ background: linear-gradient(135deg, #025EA9, #013e70); padding: 35px 30px; text-align: center; color: #ffffff; }}
        .header h1 {{ margin: 0; font-size: 24px; font-weight: 700; letter-spacing: -0.025em; }}
        .content {{ padding: 40px 30px; line-height: 1.6; }}
        .content h2 {{ color: #025EA9; margin-top: 0; font-size: 20px; font-weight: 600; }}
        .details-box {{ background-color: #f1f5f9; border-left: 4px solid #025EA9; padding: 20px; margin: 25px 0; border-radius: 6px; }}
        .details-title {{ font-weight: 700; color: #334155; margin-bottom: 12px; font-size: 14px; text-transform: uppercase; letter-spacing: 0.05em; }}
        .details-list {{ list-style: none; padding: 0; margin: 0; }}
        .details-list li {{ margin-bottom: 8px; font-size: 14px; color: #475569; }}
        .details-list li strong {{ color: #1e293b; }}
        .btn-container {{ text-align: center; margin-top: 30px; }}
        .btn {{ display: inline-block; background-color: #025EA9; color: #ffffff !important; padding: 12px 28px; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 14px; transition: background-color 0.15s ease; }}
        .btn:hover {{ background-color: #013e70; }}
        .warning-text {{ font-size: 13px; color: #64748b; margin-top: 25px; border-top: 1px solid #e2e8f0; padding-top: 20px; }}
        .footer {{ background-color: #f8fafc; padding: 25px 30px; text-align: center; font-size: 12px; color: #94a3b8; border-top: 1px solid #e2e8f0; }}
    </style>
</head>
<body>
    <div class="wrapper">
        <div class="container">
            <div class="header">
                <h1>Insurance Border</h1>
            </div>
            <div class="content">
                <h2>Dear {name},</h2>
                <p>Welcome to Insurance Border!</p>
                <p>Your account has been created successfully.</p>
                
                <div class="details-box">
                    <div class="details-title">Account Details</div>
                    <ul class="details-list">
                        <li><strong>• Name:</strong> {name}</li>
                        <li><strong>• Email:</strong> {email}</li>
                        <li><strong>• Registration Date:</strong> {current_time}</li>
                    </ul>
                </div>
                
                <p>You can now log in and start using the Insurance Border platform.</p>
                
                <div class="btn-container">
                    <a href="http://localhost:5173/signin" class="btn">Log In to Your Account</a>
                </div>
                
                <p class="warning-text">
                    If you did not create this account, please contact our support team immediately.
                </p>
                
                <p>Thank you,<br><strong>Insurance Border Team</strong></p>
            </div>
            <div class="footer">
                <p>&copy; {current_year} Insurance Border. All rights reserved.</p>
            </div>
        </div>
    </div>
</body>
</html>
"""
    return send_email(email, subject, html_content)

def send_login_notification_email(name: str, email: str, ip_address: str, browser: str, device: str) -> bool:
    """
    Sends a notification email upon successful account login.
    """
    from datetime import timezone
    current_time = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
    current_year = datetime.now(timezone.utc).year
    
    subject = "Successful Login to Your Insurance Border Account"
    
    html_content = f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Notification</title>
    <style>
        body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f8fafc; color: #1e293b; margin: 0; padding: 0; }}
        .wrapper {{ width: 100%; background-color: #f8fafc; padding: 20px 0; }}
        .container {{ max-width: 600px; margin: 0 auto; background-color: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1); border: 1px solid #e2e8f0; }}
        .header {{ background: linear-gradient(135deg, #025EA9, #013e70); padding: 35px 30px; text-align: center; color: #ffffff; }}
        .header h1 {{ margin: 0; font-size: 24px; font-weight: 700; letter-spacing: -0.025em; }}
        .content {{ padding: 40px 30px; line-height: 1.6; }}
        .content h2 {{ color: #025EA9; margin-top: 0; font-size: 20px; font-weight: 600; }}
        .details-box {{ background-color: #f1f5f9; border-left: 4px solid #025EA9; padding: 20px; margin: 25px 0; border-radius: 6px; }}
        .details-title {{ font-weight: 700; color: #334155; margin-bottom: 12px; font-size: 14px; text-transform: uppercase; letter-spacing: 0.05em; }}
        .details-list {{ list-style: none; padding: 0; margin: 0; }}
        .details-list li {{ margin-bottom: 8px; font-size: 14px; color: #475569; }}
        .details-list li strong {{ color: #1e293b; }}
        .warning-text {{ font-size: 13.5px; color: #991b1b; background-color: #fef2f2; border: 1px solid #fca5a5; padding: 15px; border-radius: 6px; margin-top: 25px; }}
        .footer {{ background-color: #f8fafc; padding: 25px 30px; text-align: center; font-size: 12px; color: #94a3b8; border-top: 1px solid #e2e8f0; }}
    </style>
</head>
<body>
    <div class="wrapper">
        <div class="container">
            <div class="header">
                <h1>Security Alert</h1>
            </div>
            <div class="content">
                <h2>Dear {name},</h2>
                <p>This is to inform you that your Insurance Border account was accessed successfully.</p>
                
                <div class="details-box">
                    <div class="details-title">Login Details</div>
                    <ul class="details-list">
                        <li><strong>• Date & Time:</strong> {current_time}</li>
                        <li><strong>• Email:</strong> {email}</li>
                        <li><strong>• IP Address:</strong> {ip_address}</li>
                        <li><strong>• Browser:</strong> {browser}</li>
                        <li><strong>• Device:</strong> {device}</li>
                    </ul>
                </div>
                
                <p>If this login was performed by you, no action is required.</p>
                
                <div class="warning-text">
                    <strong>Important Security Notice:</strong><br>
                    If you do not recognize this login activity, please change your password immediately and contact support.
                </div>
                
                <p style="margin-top: 25px;">Thank you,<br><strong>Insurance Border Team</strong></p>
            </div>
            <div class="footer">
                <p>&copy; {current_year} Insurance Border. All rights reserved.</p>
            </div>
        </div>
    </div>
</body>
</html>
"""
    return send_email(email, subject, html_content)

def send_reset_password_email(name: str, email: str, token: str) -> bool:
    """
    Sends a password reset email containing a link back to the frontend.
    """
    current_year = datetime.now().year
    # Format the reset link pointing to the frontend
    frontend_url = settings.FRONTEND_URL.rstrip('/')
    reset_url = f"{frontend_url}/reset-password?token={token}"
    
    subject = "Reset your Insurance Border Password"
    
    html_content = f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset Password</title>
    <style>
        body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f8fafc; color: #1e293b; margin: 0; padding: 0; }}
        .wrapper {{ width: 100%; background-color: #f8fafc; padding: 20px 0; }}
        .container {{ max-width: 600px; margin: 0 auto; background-color: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1); border: 1px solid #e2e8f0; }}
        .header {{ background: linear-gradient(135deg, #025EA9, #013e70); padding: 35px 30px; text-align: center; color: #ffffff; }}
        .header h1 {{ margin: 0; font-size: 24px; font-weight: 700; letter-spacing: -0.025em; }}
        .content {{ padding: 40px 30px; line-height: 1.6; }}
        .content h2 {{ color: #025EA9; margin-top: 0; font-size: 20px; font-weight: 600; }}
        .btn-container {{ text-align: center; margin-top: 30px; }}
        .btn {{ display: inline-block; background-color: #025EA9; color: #ffffff !important; padding: 12px 28px; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 14px; transition: background-color 0.15s ease; }}
        .btn:hover {{ background-color: #013e70; }}
        .link-text {{ word-break: break-all; font-size: 13px; color: #64748b; margin-top: 15px; text-align: center; }}
        .warning-text {{ font-size: 13px; color: #64748b; margin-top: 25px; border-top: 1px solid #e2e8f0; padding-top: 20px; }}
        .footer {{ background-color: #f8fafc; padding: 25px 30px; text-align: center; font-size: 12px; color: #94a3b8; border-top: 1px solid #e2e8f0; }}
    </style>
</head>
<body>
    <div class="wrapper">
        <div class="container">
            <div class="header">
                <h1>Insurance Border</h1>
            </div>
            <div class="content">
                <h2>Dear {name},</h2>
                <p>We received a request to reset the password for your Insurance Border account.</p>
                <p>Please click the button below to set a new password. This link is valid for 15 minutes.</p>
                
                <div class="btn-container">
                    <a href="{reset_url}" class="btn">Reset Password</a>
                </div>
                
                <p class="link-text">
                    If the button doesn't work, copy and paste this link into your browser:<br>
                    <a href="{reset_url}">{reset_url}</a>
                </p>
                
                <p class="warning-text">
                    If you did not request a password reset, please ignore this email. Your password will remain unchanged.
                </p>
                
                <p>Thank you,<br><strong>Insurance Border Team</strong></p>
            </div>
            <div class="footer">
                <p>&copy; {current_year} Insurance Border. All rights reserved.</p>
            </div>
        </div>
    </div>
</body>
</html>
"""
    return send_email(email, subject, html_content)

def send_password_change_otp_email(name: str, email: str, otp_code: str) -> bool:
    """
    Sends a password change OTP verification email.
    """
    current_year = datetime.now().year
    subject = "Change your Insurance Border Password"
    
    html_content = f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify Password Change</title>
    <style>
        body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f8fafc; color: #1e293b; margin: 0; padding: 0; }}
        .wrapper {{ width: 100%; background-color: #f8fafc; padding: 20px 0; }}
        .container {{ max-width: 600px; margin: 0 auto; background-color: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1); border: 1px solid #e2e8f0; }}
        .header {{ background: linear-gradient(135deg, #025EA9, #013e70); padding: 35px 30px; text-align: center; color: #ffffff; }}
        .header h1 {{ margin: 0; font-size: 24px; font-weight: 700; letter-spacing: -0.025em; }}
        .content {{ padding: 40px 30px; line-height: 1.6; }}
        .content h2 {{ color: #025EA9; margin-top: 0; font-size: 20px; font-weight: 600; }}
        .otp-box {{ background-color: #f1f5f9; padding: 20px; text-align: center; margin: 25px 0; border-radius: 8px; border: 1px dashed #025EA9; }}
        .otp-code {{ font-size: 32px; font-weight: 800; letter-spacing: 0.2em; color: #025EA9; margin: 0; }}
        .warning-text {{ font-size: 13.5px; color: #991b1b; background-color: #fef2f2; border: 1px solid #fca5a5; padding: 15px; border-radius: 6px; margin-top: 25px; }}
        .footer {{ background-color: #f8fafc; padding: 25px 30px; text-align: center; font-size: 12px; color: #94a3b8; border-top: 1px solid #e2e8f0; }}
    </style>
</head>
<body>
    <div class="wrapper">
        <div class="container">
            <div class="header">
                <h1>Security Verification</h1>
            </div>
            <div class="content">
                <h2>Dear {name},</h2>
                <p>We received a request to change the password for your Insurance Border account.</p>
                <p>Please use the following 6-digit verification code to complete the process. This code is valid for 10 minutes.</p>
                
                <div class="otp-box">
                    <p class="otp-code">{otp_code}</p>
                </div>
                
                <div class="warning-text">
                    <strong>Important Security Notice:</strong><br>
                    If you did not request this password change, please ignore this email and secure your account immediately.
                </div>
                
                <p style="margin-top: 25px;">Thank you,<br><strong>Insurance Border Team</strong></p>
            </div>
            <div class="footer">
                <p>&copy; {current_year} Insurance Border. All rights reserved.</p>
            </div>
        </div>
    </div>
</body>
</html>
"""
    return send_email(email, subject, html_content)
