import os
import sys
import smtplib
import logging
from time import time
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# SMTP Configuration
SMTP_SERVER = 'thecrossingway.com'
SMTP_PORT = 587
SMTP_USERNAME = 'xinfoadminx@thecrossingway.com'
SMTP_PASSWORD = 'ypc?/%9tP#!2%'

# Logging Setup
LOG_FILE = "email.log"
logging.basicConfig(
    filename=LOG_FILE,
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] - %(message)s"))
logging.getLogger().addHandler(console_handler)

def load_template(template_filename, caseid, link, rep):
    """Loads and formats an email template."""
    template_path = os.path.join("templates", f"{template_filename}.html")
    start_time = time()
    
    try:
        with open(template_path, "r", encoding="utf-8") as file:
            html_content = file.read()
        
        html_content = html_content.replace("{{CASE_ID}}", caseid).replace("{{LINK}}", link).replace("{{REP}}", rep)
        logging.info(f"Template '{template_filename}' loaded in {time() - start_time:.3f} sec.")
        return html_content
    except FileNotFoundError:
        logging.error(f"Template file '{template_filename}' not found.")
        sys.exit(1)
    except Exception as e:
        logging.error(f"Error reading template file: {e}")
        sys.exit(1)

def send_email(to_email, subject, html_content):
    msg = MIMEMultipart("alternative")
    msg["Subject"] = subject
    msg["From"] = formataddr(("Support", "support@security-gle.com"))
    msg["To"] = to_email
    msg.attach(MIMEText(html_content, "html"))

    start_time = time()
    try:
        logging.info(f"Connecting to SMTP {SMTP_SERVER}:{SMTP_PORT}...")
        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT, timeout=10) as smtp:
            smtp.ehlo()
            smtp.starttls()
            smtp.login(SMTP_USERNAME, SMTP_PASSWORD)
            smtp.sendmail(SMTP_USERNAME, to_email, msg.as_string())
        
        logging.info(f"Email sent to {to_email} in {time() - start_time:.3f} sec.")
        sys.exit(0)
    except Exception as e:
        logging.error(f"Failed to send email to {to_email}: {e}")
        sys.exit(1)

if __name__ == "__main__":
    if len(sys.argv) < 7:
        logging.error("Insufficient arguments. Usage: script.py <to_email> <subject> <template> <caseid> <link> <rep>")
        sys.exit(1)

    to_email = sys.argv[1]
    subject = sys.argv[2]
    templ = sys.argv[3]
    caseid = sys.argv[4]
    link = sys.argv[5]
    rep = sys.argv[6]

    logging.info(f"Preparing email for {to_email} | Subject: {subject} | Template: {templ}")
    html_content = load_template(templ, caseid, link, rep)
    send_email(to_email, subject, html_content)
