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

logger = logging.getLogger('adimsayar')

def send_verification_email(recipient: str, verification_code: str) -> bool:
    """
    Send an email with the verification code using SMTP.
    The settings should configure:
      - MAIL_FROM_ADDRESS, MAIL_HOST, MAIL_PORT, MAIL_USERNAME,
        MAIL_PASSWORD, and MAIL_ENCRYPTION.
    """
    try:
        sender = settings.MAIL_FROM_ADDRESS
        mail_host = settings.MAIL_HOST
        mail_port = settings.MAIL_PORT  # 예: 587
        mail_username = settings.MAIL_USERNAME
        mail_password = settings.MAIL_PASSWORD
        mail_encryption = settings.MAIL_ENCRYPTION  # 예: "tls"

        # 이메일 메시지 생성
        message = MIMEMultipart("alternative")
        message["Subject"] = "Your Verification Code"
        message["From"] = sender
        message["To"] = recipient

        text = f"Your verification code is: {verification_code}"
        html = f"""
        <html>
            <body>
                <p>Your verification code is: <strong>{verification_code}</strong></p>
            </body>
        </html>
        """

        part1 = MIMEText(text, "plain")
        part2 = MIMEText(html, "html")
        message.attach(part1)
        message.attach(part2)

        # SMTP 서버에 연결
        server = smtplib.SMTP(mail_host, mail_port)
        if mail_encryption.lower() == "tls":
            server.starttls()
        server.login(mail_username, mail_password)
        server.sendmail(sender, recipient, message.as_string())
        server.quit()

        logger.info(f"Verification email sent to {recipient}")
        return True
    except Exception as e:
        logger.error(f"Error sending verification email: {str(e)}", exc_info=True)
        return False
