import os
import smtplib
from email.message import EmailMessage
from typing import Optional, Sequence


from dotenv import load_dotenv

load_dotenv()

SMTP_HOST = os.getenv("SMTP_HOST", "smtp.gmail.com")
SMTP_PORT = int(os.getenv("SMTP_PORT", "587"))
SMTP_USER = os.getenv("SMTP_USER", "")
SMTP_PASS = os.getenv("SMTP_PASS", "")
SMTP_FROM = os.getenv("SMTP_FROM", SMTP_USER or "no-reply@example.com")
SMTP_FROM_NAME = os.getenv("SMTP_FROM_NAME", "Nbitz")
SMTP_USE_TLS = os.getenv("SMTP_USE_TLS", "true").lower() in {"1", "true", "yes", "on"}
SMTP_USE_SSL = os.getenv("SMTP_USE_SSL", "false").lower() in {"1", "true", "yes", "on"}
SMTP_TIMEOUT = int(os.getenv("SMTP_TIMEOUT", "30"))
SMTP_DEBUG = os.getenv("SMTP_DEBUG", "false").lower() in {"1", "true", "yes", "on"}


def _build_message(subject: str, to: Sequence[str], html: Optional[str] = None, text: Optional[str] = None) -> EmailMessage:
    msg = EmailMessage()
    from_display = f"{SMTP_FROM_NAME} <{SMTP_FROM}>" if SMTP_FROM_NAME else SMTP_FROM
    msg["From"] = from_display
    msg["To"] = ", ".join(to)
    msg["Subject"] = subject
    if html and text:
        msg.set_content(text)
        msg.add_alternative(html, subtype="html")
    elif html:
        # Generate a plain text fallback
        msg.set_content("This email contains HTML content. Please use an HTML-capable client.")
        msg.add_alternative(html, subtype="html")
    elif text:
        msg.set_content(text)
    else:
        msg.set_content("")
    return msg


def send_email(subject: str, to: Sequence[str], html: Optional[str] = None, text: Optional[str] = None) -> None:
    if not SMTP_HOST:
        raise RuntimeError("SMTP_HOST is not configured")

    # Proactive validation for Gmail setup to avoid 530 Authentication Required
    is_gmail = "gmail" in SMTP_HOST.lower() or "google" in SMTP_HOST.lower()
    if is_gmail:
        if not SMTP_USER or not SMTP_PASS:
            raise RuntimeError(
                "SMTP_USER/SMTP_PASS not configured. For Gmail, set SMTP_USER to your Gmail "
                "address and SMTP_PASS to a Gmail App Password (not your normal password)."
            )
        if SMTP_FROM.lower() != SMTP_USER.lower():
            raise RuntimeError(
                "For Gmail SMTP, SMTP_FROM must match SMTP_USER. Set SMTP_FROM to the same Gmail address."
            )

    msg = _build_message(subject, to, html=html, text=text)

    if SMTP_USE_SSL:
        with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT, timeout=SMTP_TIMEOUT) as server:
            if SMTP_DEBUG:
                server.set_debuglevel(1)
            if SMTP_USER and SMTP_PASS:
                server.login(SMTP_USER, SMTP_PASS)
            server.send_message(msg)
            return

    with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=SMTP_TIMEOUT) as server:
        if SMTP_DEBUG:
            server.set_debuglevel(1)
        server.ehlo()
        if SMTP_USE_TLS:
            server.starttls()
            server.ehlo()
        if SMTP_USER and SMTP_PASS:
            server.login(SMTP_USER, SMTP_PASS)
        server.send_message(msg)


