"""
SL CAT TOPUP - Email Service Module
Handles sending OTP verification emails and official Order Receipts with Web Promo
Sender: SL cat app <slcatapp@gmail.com>
"""

import smtplib
import ssl
import logging
import threading
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import make_msgid, formatdate
from datetime import datetime
from typing import Optional, Dict, Any

logger = logging.getLogger("MailService")

GMAIL_USER = "slcatapp@gmail.com"
GMAIL_SENDER_NAME = "SL CAT TOPUP"
STORE_URL = "https://topupshop.slcatvpn.bid"
WHATSAPP_SUPPORT = "+63 910 456 8696"
WHATSAPP_URL = "https://wa.me/639104568696"


def get_smtp_password() -> str:
    """Retrieves Google App Password from database settings or config."""
    try:
        from database import get_setting
        pwd = get_setting("smtp_password", "") or get_setting("email_app_password", "")
        if pwd:
            return pwd.strip().replace(" ", "")
    except Exception:
        pass

    try:
        import config
        pwd = getattr(config, "EMAIL_APP_PASSWORD", "")
        if pwd:
            return pwd.strip().replace(" ", "")
    except Exception:
        pass

    return ""


def send_email_smtp_with_status(to_email: str, subject: str, html_content: str, text_content: str = "") -> tuple:
    """
    Sends an email using Gmail SMTP and returns (success: bool, error_message: str).
    """
    to_email = (to_email or "").strip()
    if not to_email or "@" not in to_email:
        logger.warning(f"Invalid recipient email: {to_email}")
        return False, "වලංගු නොවන ඊමේල් ලිපිනයක් (Invalid recipient email)."

    password = get_smtp_password()
    if not password:
        logger.warning("Gmail App Password not configured in settings or config.py. Email skipped.")
        return False, "Gmail App Password එක Admin Panel එකේ සකසා නැත. කරුණාකර Admin Panel එකෙන් slcatapp@gmail.com සඳහා Google App Password එක Save කරන්න."

    msg = MIMEMultipart("alternative")
    msg["Subject"] = subject
    msg["From"] = f"{GMAIL_SENDER_NAME} <{GMAIL_USER}>"
    msg["To"] = to_email
    msg["Reply-To"] = GMAIL_USER
    msg["Date"] = formatdate(localtime=True)
    msg["Message-ID"] = make_msgid(domain="gmail.com")
    msg["MIME-Version"] = "1.0"
    msg["X-Mailer"] = "SL CAT TOPUP Automated Gateway"
    msg["Auto-Submitted"] = "auto-generated"
    msg["X-Auto-Response-Suppress"] = "OOF, AutoReply"
    msg["X-Priority"] = "1"

    if text_content:
        msg.attach(MIMEText(text_content, "plain", "utf-8"))
    msg.attach(MIMEText(html_content, "html", "utf-8"))

    # Try SSL 465 first
    try:
        context = ssl.create_default_context()
        with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context, timeout=12) as server:
            server.login(GMAIL_USER, password)
            server.sendmail(GMAIL_USER, to_email, msg.as_string())
            logger.info(f"✅ Email sent successfully to {to_email} via SMTP_SSL (465)")
            return True, "Email sent successfully"
    except Exception as e_ssl:
        logger.warning(f"SMTP_SSL (465) failed: {e_ssl}. Attempting STARTTLS (587)...")
        try:
            with smtplib.SMTP("smtp.gmail.com", 587, timeout=12) as server:
                server.ehlo()
                server.starttls()
                server.ehlo()
                server.login(GMAIL_USER, password)
                server.sendmail(GMAIL_USER, to_email, msg.as_string())
                logger.info(f"✅ Email sent successfully to {to_email} via STARTTLS (587)")
                return True, "Email sent successfully"
        except smtplib.SMTPAuthenticationError as e_auth:
            logger.error(f"❌ Gmail Authentication Error: {e_auth}")
            return False, "Google මඟින් Password එක ප්‍රතික්ෂේප විය (535 Authentication Failed). සාමාන්‍ය Gmail Password එක වෙනුවට Google Security වෙතින් ලබාගත් 16-Digit App Password එකක් ඇතුළත් කරන්න."
        except Exception as e_tls:
            logger.error(f"❌ Failed to send email to {to_email}: {e_tls}")
            err_str = str(e_tls)
            if "timed out" in err_str.lower() or "timeout" in err_str.lower() or "refused" in err_str.lower():
                return False, f"Hosting Server එකෙන් පිටතට යන Email Ports (465/587) අවහිර කර ඇත (Connection Timed Out: {err_str})."
            return False, f"SMTP Error: {err_str}"


def send_email_smtp(to_email: str, subject: str, html_content: str, text_content: str = "") -> bool:
    """Sends an email using Gmail SMTP and returns boolean."""
    success, _ = send_email_smtp_with_status(to_email, subject, html_content, text_content)
    return success


def send_otp_email_async(to_email: str, otp_code: str, user_name: str = ""):
    """Sends OTP verification email in background thread."""
    threading.Thread(
        target=_send_otp_email_sync,
        args=(to_email, otp_code, user_name),
        daemon=True,
    ).start()


def send_otp_email_sync_with_status(to_email: str, otp_code: str, user_name: str = "") -> tuple:
    subject = f"{otp_code} is your SL CAT TOPUP verification code"
    name_display = user_name.strip() if user_name else "Gamer"
    html = _build_otp_email_html(otp_code, name_display)
    text = (
        f"Hello {name_display},\n\n"
        f"Your SL CAT TOPUP verification code is: {otp_code}\n\n"
        f"This code is valid for 10 minutes.\n"
        f"If you did not request this code, please ignore this message.\n\n"
        f"SL CAT TOPUP ({GMAIL_USER})"
    )
    return send_email_smtp_with_status(to_email, subject, html, text)


def _send_otp_email_sync(to_email: str, otp_code: str, user_name: str = ""):
    send_otp_email_sync_with_status(to_email, otp_code, user_name)


def _build_otp_email_html(otp_code: str, name_display: str) -> str:
    return f"""<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>SL CAT TOPUP Verification Code</title>
</head>
<body style="margin: 0; padding: 0; background-color: #f8fafc; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #1e293b;">
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color: #f8fafc; padding: 30px 10px;">
    <tr>
      <td align="center">
        <table role="presentation" width="100%" style="max-width: 480px; background: #ffffff; border: 1px solid #e2e8f0; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.06);" cellspacing="0" cellpadding="0">
          
          <!-- BRAND HEADER -->
          <tr>
            <td style="padding: 22px 28px; background: #0f172a; text-align: left; border-bottom: 3px solid #0284c7;">
              <h2 style="margin: 0; font-size: 18px; font-weight: 800; color: #ffffff; letter-spacing: 0.5px;">SL CAT TOPUP</h2>
              <span style="font-size: 11px; color: #94a3b8;">Account Security Verification</span>
            </td>
          </tr>

          <!-- BODY -->
          <tr>
            <td style="padding: 28px;">
              <p style="font-size: 15px; color: #334155; margin-top: 0; margin-bottom: 14px; line-height: 1.5;">
                Hello <strong>{name_display}</strong>,
              </p>
              <p style="font-size: 14px; color: #475569; margin: 0 0 20px 0; line-height: 1.5;">
                Please use the following single-use verification code to complete your security verification on SL CAT TOPUP:
              </p>

              <!-- OTP BOX -->
              <div style="background: #f1f5f9; border: 1px solid #cbd5e1; border-radius: 8px; padding: 18px; text-align: center; margin: 20px 0;">
                <div style="font-size: 11px; text-transform: uppercase; letter-spacing: 1.5px; color: #64748b; font-weight: 700; margin-bottom: 6px;">Security Verification Code</div>
                <div style="font-size: 34px; font-weight: 800; color: #0284c7; letter-spacing: 8px; font-family: monospace;">{otp_code}</div>
                <div style="font-size: 12px; color: #64748b; margin-top: 6px;">Valid for 10 minutes</div>
              </div>

              <p style="font-size: 13px; color: #64748b; margin: 20px 0 0 0; line-height: 1.5;">
                If you did not initiate this request, you can safely ignore this email. Do not share this code with anyone.
              </p>
            </td>
          </tr>

          <!-- FOOTER -->
          <tr>
            <td style="padding: 16px 28px; background: #f8fafc; border-top: 1px solid #e2e8f0; font-size: 11px; color: #94a3b8; text-align: center; line-height: 1.5;">
              Automated message from SL CAT TOPUP ({GMAIL_USER}).<br>
              © {datetime.now().year} SL CAT TOPUP. All rights reserved.
            </td>
          </tr>

        </table>
      </td>
    </tr>
  </table>
</body>
</html>"""


def send_order_receipt_email_async(to_email: str, order: Dict[str, Any]):
    """Sends official order receipt with web promo in background thread."""
    threading.Thread(
        target=_send_order_receipt_email_sync,
        args=(to_email, order),
        daemon=True,
    ).start()


def send_order_receipt_email_sync_with_status(to_email: str, order: Dict[str, Any]) -> tuple:
    order_code = order.get("order_code", "CAT-ORDER")
    player_id = order.get("player_id", "N/A")
    nickname = order.get("player_nickname") or "Free Fire Player"
    product_name = order.get("product_name") or "Free Fire Diamonds"
    amount = float(order.get("amount", 0.0))
    created_at = order.get("created_at") or datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    customer_name = order.get("customer_name") or nickname

    subject = f"Receipt for Order #{order_code} - SL CAT TOPUP"
    html = _build_receipt_email_html(order_code, player_id, product_name, amount, created_at, customer_name)
    text = (
        f"Hello {customer_name},\n\n"
        f"Thank you for your order with SL CAT TOPUP. Your order has been completed successfully.\n\n"
        f"ORDER SUMMARY:\n"
        f"-----------------------------------------\n"
        f"Order ID:    #{order_code}\n"
        f"Date:        {created_at}\n"
        f"Player UID:  {player_id}\n"
        f"Product:     {product_name}\n"
        f"Amount:      Rs. {amount:,.2f}\n"
        f"Status:      Completed / Delivered\n"
        f"-----------------------------------------\n\n"
        f"Official Web Store: {STORE_URL}\n"
        f"WhatsApp Support:   {WHATSAPP_SUPPORT}\n\n"
        f"Thank you for choosing SL CAT TOPUP.\n"
        f"Automated notification from {GMAIL_USER}"
    )
    return send_email_smtp_with_status(to_email, subject, html, text)


def _send_order_receipt_email_sync(to_email: str, order: Dict[str, Any]) -> bool:
    success, _ = send_order_receipt_email_sync_with_status(to_email, order)
    return success


def _build_receipt_email_html(order_code: str, player_id: str, product_name: str, amount: float, created_at: str, customer_name: str) -> str:
    return f"""<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Receipt for Order #{order_code} - SL CAT TOPUP</title>
</head>
<body style="margin: 0; padding: 0; background-color: #f8fafc; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #1e293b;">
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color: #f8fafc; padding: 30px 10px;">
    <tr>
      <td align="center">
        <table role="presentation" width="100%" style="max-width: 520px; background: #ffffff; border: 1px solid #e2e8f0; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.06);" cellspacing="0" cellpadding="0">
          
          <!-- BRAND HEADER -->
          <tr>
            <td style="padding: 24px 28px; background: #0f172a; text-align: left; border-bottom: 3px solid #0284c7;">
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <div>
                  <h2 style="margin: 0; font-size: 19px; font-weight: 800; color: #ffffff; letter-spacing: 0.5px;">SL CAT TOPUP</h2>
                  <span style="font-size: 12px; color: #94a3b8;">Official Order Receipt</span>
                </div>
              </div>
            </td>
          </tr>

          <!-- BODY -->
          <tr>
            <td style="padding: 28px;">
              <p style="font-size: 15px; color: #334155; margin-top: 0; margin-bottom: 12px; line-height: 1.5;">
                Hello <strong>{customer_name}</strong>,
              </p>
              <p style="font-size: 14px; color: #475569; margin: 0 0 20px 0; line-height: 1.5;">
                Thank you for your order. Your top-up has been successfully processed and delivered to your Free Fire account.
              </p>

              <!-- STATUS BADGE -->
              <div style="background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 6px; padding: 10px 14px; margin-bottom: 20px; display: inline-block;">
                <span style="color: #166534; font-size: 13px; font-weight: 700;">✓ Order Completed & Delivered</span>
              </div>

              <!-- RECEIPT TABLE -->
              <table width="100%" cellspacing="0" cellpadding="0" style="border-collapse: collapse; border: 1px solid #e2e8f0; border-radius: 8px; overflow: hidden; margin-bottom: 22px;">
                <tr style="background: #f8fafc; border-bottom: 1px solid #e2e8f0;">
                  <td style="padding: 10px 14px; font-size: 12px; font-weight: 700; color: #64748b; width: 40%;">Order Code</td>
                  <td style="padding: 10px 14px; font-size: 13px; font-weight: 700; color: #0284c7; font-family: monospace;">#{order_code}</td>
                </tr>
                <tr style="border-bottom: 1px solid #e2e8f0;">
                  <td style="padding: 10px 14px; font-size: 12px; font-weight: 700; color: #64748b;">Player UID</td>
                  <td style="padding: 10px 14px; font-size: 13px; font-weight: 600; color: #1e293b; font-family: monospace;">{player_id}</td>
                </tr>
                <tr style="border-bottom: 1px solid #e2e8f0;">
                  <td style="padding: 10px 14px; font-size: 12px; font-weight: 700; color: #64748b;">Product / Package</td>
                  <td style="padding: 10px 14px; font-size: 13px; font-weight: 600; color: #1e293b;">{product_name}</td>
                </tr>
                <tr style="border-bottom: 1px solid #e2e8f0;">
                  <td style="padding: 10px 14px; font-size: 12px; font-weight: 700; color: #64748b;">Amount Paid</td>
                  <td style="padding: 10px 14px; font-size: 15px; font-weight: 800; color: #0f172a;">Rs. {amount:,.2f}</td>
                </tr>
                <tr>
                  <td style="padding: 10px 14px; font-size: 12px; font-weight: 700; color: #64748b;">Date & Time</td>
                  <td style="padding: 10px 14px; font-size: 12px; color: #64748b;">{created_at}</td>
                </tr>
              </table>

              <!-- WEB STORE & SUPPORT NOTICE -->
              <div style="background: #f1f5f9; border: 1px solid #cbd5e1; border-radius: 8px; padding: 14px 16px; margin: 20px 0; font-size: 13px; color: #334155; line-height: 1.5;">
                <div style="font-weight: 700; margin-bottom: 4px; color: #0f172a;">Official Store & Support</div>
                <div>Web Store: <a href="{STORE_URL}" style="color: #0284c7; font-weight: 600; text-decoration: underline;">{STORE_URL}</a></div>
                <div style="margin-top: 4px;">WhatsApp Help: <a href="{WHATSAPP_URL}" style="color: #15803d; font-weight: 600; text-decoration: underline;">{WHATSAPP_SUPPORT}</a></div>
              </div>

              <p style="font-size: 12px; color: #94a3b8; margin: 16px 0 0 0; line-height: 1.5;">
                ස්තුතියි! SL CAT TOPUP සමඟ රැඳී සිටින ඔබට විශේෂ ස්තුතිය. ඉදිරි Top-Up සඳහා අපගේ නිල වෙබ් අඩවිය භාවිතා කරන්න.
              </p>
            </td>
          </tr>

          <!-- FOOTER -->
          <tr>
            <td style="padding: 16px 28px; background: #f8fafc; border-top: 1px solid #e2e8f0; font-size: 11px; color: #94a3b8; text-align: center; line-height: 1.5;">
              Automated transaction receipt from SL CAT TOPUP ({GMAIL_USER}).<br>
              © {datetime.now().year} SL CAT TOPUP. All rights reserved.
            </td>
          </tr>

        </table>
      </td>
    </tr>
  </table>
</body>
</html>"""
