import os
import smtplib
import traceback
import logging
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from email.utils import formataddr
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Email configuration
SMTP_SERVER = os.getenv('SMTP_SERVER')
SMTP_PORT = os.getenv('SMTP_PORT')
SMTP_USER = os.getenv('SMTP_USER')
SMTP_PASSWORD = os.getenv('SMTP_PASSWORD')
SENDER_EMAIL = os.getenv('SENDER_EMAIL')
# Split env recipient lists safely and strip whitespace; default to empty list
def _split_env_list(varname):
    raw = os.getenv(varname, '')
    return [s.strip() for s in raw.split(',') if s.strip()]

EMAIL_RECIPIENTS = _split_env_list('EMAIL_RECIPIENTS')
ERROR_EMAIL_RECIPIENTS = _split_env_list('ERROR_EMAIL_RECIPIENTS')
SUCCESS_EMAIL_RECIPIENTS = _split_env_list('SUCCESS_EMAIL_RECIPIENTS')


# Send email with attachment
def send_email_with_attachment(subject, body, attachment_path=None, email_recipients=None):
    sender_name="Art.c.hive Support for ARKIVO"
    try:
        # Create a multipart message
        msg = MIMEMultipart()
        msg['From'] =  formataddr((sender_name, SENDER_EMAIL))
        # if email recipent not defined use EMAIL_RECIPIENTS 
        if email_recipients:
            msg['To'] = ', '.join(email_recipients)
        else:
            msg['To'] = ', '.join(EMAIL_RECIPIENTS)

        msg['Subject'] = subject

        # Attach the body with the msg instance
        msg.attach(MIMEText(body, 'plain'))

        # Attach the file if provided
        if attachment_path:
            if os.path.exists(attachment_path):
                with open(attachment_path, "rb") as attachment:
                    part = MIMEBase('application', 'octet-stream')
                    part.set_payload(attachment.read())
                    encoders.encode_base64(part)
                    part.add_header('Content-Disposition', f'attachment; filename= {os.path.basename(attachment_path)}')
                    msg.attach(part)
            else:
                logging.warning(f"Attachment path {attachment_path} does not exist. Skipping attachment.")

        # Create SMTP session for sending the mail
        recipients_list = email_recipients if email_recipients else EMAIL_RECIPIENTS
        if isinstance(recipients_list, str):
            recipients_list = [recipients_list]
        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
            server.starttls()  # Enable security
            server.login(SMTP_USER, SMTP_PASSWORD)  # Login with mail_id and password
            text = msg.as_string()
            server.sendmail(SENDER_EMAIL, recipients_list, text)
        
        logging.info("Email sent successfully.")
    except Exception as e:
        logging.error(f"Failed to send email: {e}")

# Create the email message
def send_error_email(subject, body, recipients):
    try:
        sender_email = os.getenv('SENDER_EMAIL')
        smtp_server = os.getenv('SMTP_SERVER')
        smtp_port = int(os.getenv('SMTP_PORT'))
        smtp_user = os.getenv('SMTP_USER')
        smtp_password = os.getenv('SMTP_PASSWORD')

        msg = MIMEMultipart()
        msg['From'] = sender_email
        msg['To'] = ", ".join(recipients)
        msg['Subject'] = subject
        msg.attach(MIMEText(body, 'plain'))

        with smtplib.SMTP(smtp_server, smtp_port) as server:
            server.starttls()
            server.login(smtp_user, smtp_password)
            server.sendmail(sender_email, recipients, msg.as_string())

        logging.error("Error email sent successfully")
    except Exception as e:
        logging.error(f"Failed to send error email: {e}")

# Handle error
def handle_error(e):
    error_trace = traceback.format_exc()
    subject = "Error Notification"
    body = f"An error occurred:\n\n{error_trace}"
    recipients = os.getenv('EMAIL_RECIPIENTS', '').split(',')
    send_error_email(subject, body, recipients)
    raise e
