import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from typing import List, Union
from fastapi import APIRouter
import os
from dotenv import load_dotenv

load_dotenv()
router = APIRouter()

# SMTP Configurations
SMTP_SERVER = os.getenv('SMTP_SERVER', 'smtp.google.com')
SMTP_PORT = os.getenv('SMTP_PORT', 465)  # Typically 587 for TLS or 465 for SSL
SMTP_USERNAME = os.getenv('SMTP_USERNAME', 'nanda@movex.ai') 
SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', 'sljf ppbd orvc bkss')
FROM_EMAIL =os.getenv('FROM_EMAIL', 'thought@movex.ai')

@router.post("/send_email/")
def send_email(subject: str, body: str, to_email: Union[str, List[str]], cc_emails: List[str] = None, bcc_emails: List[str] = None):
    """
    Sends an email using the given SMTP configurations.

    Args:
    - subject (str): Subject of the email.
    - body (str): Body content of the email, in HTML format.
    - to_email (Union[str, List[str]]): Recipient email address or addresses.
    - cc_emails (List[str], optional): List of CC email addresses.
    - bcc_emails (List[str], optional): List of BCC email addresses.

    Returns:
    None
    """
    # Create a MIMEMultipart object
    msg = MIMEMultipart()
    msg["Subject"] = subject
    msg["From"] = FROM_EMAIL

    # Convert to_email to a list if it's a string
    if isinstance(to_email, str):
        to_email = [to_email]
    
    msg["To"] = ", ".join(to_email)

    if cc_emails:
        msg["Cc"] = ", ".join(cc_emails)

    # Create a MIMEText part
    part = MIMEText(body, 'html')  # Specify 'html' for HTML content
    msg.attach(part)

    recipients = to_email + (cc_emails or []) + (bcc_emails or [])

    print(" SMTP, ",SMTP_SERVER , "PORT", SMTP_PORT )

    try:
        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
            server.starttls()  # For security
            server.login(SMTP_USERNAME, SMTP_PASSWORD)
            server.sendmail(FROM_EMAIL, recipients, msg.as_string())
        print("Email sent successfully.")
    except Exception as e:
        print(f"Failed to send email: {e}")
