import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import time
import random
import os
import string
import html2text

# ================== CONFIGURARE ==================
DELAY_BETWEEN_EMAILS = 1.0
SMTP_FILE = "smtp.txt"
EMAILS_FILE = "emails.txt"
SENDERS_FILE = "senders.txt"
FROM_EMAILS_FILE = "mail.txt"          # ← NOU
SUBJECTS_FILE = "subject.txt"
LETTER_FILES = [f"letter{i}.html" for i in range(1, 11)]

# ================== FUNCȚII ==================
def load_smtps(filename=SMTP_FILE):
    smtps = []
    with open(filename, "r", encoding="utf-8", errors="ignore") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            parts = line.split()
            if len(parts) >= 5:
                ip = parts[0]
                port = parts[1]
                security = parts[2]
                email = parts[3]
                password = ' '.join(parts[4:])
                smtps.append({
                    "server": ip,
                    "port": int(port),
                    "security": security.upper(),
                    "user": email,
                    "password": password
                })
    return smtps


def load_recipients(filename=EMAILS_FILE):
    recipients = []
    with open(filename, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            parts = [p.strip() for p in line.split(',')]
            if len(parts) >= 3:
                recipients.append((
                    f"{parts[0]} {parts[1]}".strip(),
                    parts[0],
                    parts[1],
                    parts[2]
                ))
    return recipients


def load_file(filename):
    with open(filename, "r", encoding="utf-8") as f:
        return [line.strip() for line in f if line.strip()]


def load_from_emails(filename=FROM_EMAILS_FILE):
    if not os.path.isfile(filename):
        print(f"⚠️ Fișierul {filename} nu există. Se folosește email-ul din SMTP.")
        return None
    with open(filename, "r", encoding="utf-8") as f:
        emails = [line.strip() for line in f if line.strip() and not line.startswith('#')]
    print(f"✅ Încărcate {len(emails)} adrese From din {filename}")
    return emails if emails else None


def load_random_letter():
    available = []
    for fname in LETTER_FILES:
        if os.path.isfile(fname):
            with open(fname, "r", encoding="utf-8") as f:
                available.append(f.read())
    if not available:
        raise FileNotFoundError("Nu s-au găsit șabloane HTML valide!")
    return random.choice(available)


def generate_order_id(length=8):
    chars = string.ascii_uppercase + string.digits
    return ''.join(random.choices(chars, k=length))


def personalize_text(text, prenume, nume, order_id):
    if not text:
        return text

    client = f"{prenume} {nume}".strip()

    replacements = {
        "#PRENUME#": prenume or "prietene",
        "#NUME#": nume or "",
        "#CLIENT#": client or "prietene",
        "#ORDERID#": order_id,
    }

    for key, value in replacements.items():
        text = text.replace(key, value)

    return text


def send_single_email(recipient_data, smtp_list, senders_name, subjects_list, from_emails_list):
    nume_complet, prenume, nume, to_email = recipient_data

    try:
        smtp = random.choice(smtp_list)
        sender_name = random.choice(senders_name) if senders_name else "X"

        # Alegere From email
        if from_emails_list:
            from_email_used = random.choice(from_emails_list)
        else:
            from_email_used = smtp["user"]

        current_order_id = generate_order_id()

        html_template = load_random_letter()
        html_content = personalize_text(html_template, prenume, nume, current_order_id)
        text_content = html2text.html2text(html_content)

        subject_template = random.choice(subjects_list) if subjects_list else "Notification"
        subject = personalize_text(subject_template, prenume, nume, current_order_id)

        msg = MIMEMultipart("alternative")
        msg["Subject"] = subject
        msg["From"] = f"{sender_name} <{from_email_used}>"
        msg["To"] = to_email

        msg.attach(MIMEText(text_content, "plain", "utf-8"))
        msg.attach(MIMEText(html_content, "html", "utf-8"))

        print(
            f"[{to_email}] ({nume_complet}) "
            f"From: {from_email_used} | OrderID={current_order_id} ... ",
            end="",
            flush=True
        )

        server = smtplib.SMTP(smtp["server"], smtp["port"], timeout=20)
        server.ehlo()

        if smtp["security"] in ["STARTTLS", "TLS"]:
            server.starttls()
            server.ehlo()

        server.login(smtp["user"], smtp["password"])
        server.send_message(msg)
        server.quit()

        print("OK")
        return True

    except Exception as e:
        print(f"EȘEC → {str(e)}")
        return False


# ================== MAIN ==================
smtp_list = load_smtps()
recipients = load_recipients()
senders_name = load_file(SENDERS_FILE)
subjects_list = load_file(SUBJECTS_FILE)
from_emails_list = load_from_emails()   # ← NOU

if not smtp_list or not recipients:
    print("Verificați fișierele SMTP și destinatari!")
    exit(1)

success_count = 0
fail_count = 0

for i, recipient in enumerate(recipients, 1):
    print(f"[{i:3d}/{len(recipients):3d}] ", end="")

    success = send_single_email(
        recipient,
        smtp_list,
        senders_name,
        subjects_list,
        from_emails_list
    )

    if success:
        success_count += 1
    else:
        fail_count += 1

    if i < len(recipients):
        sleep_time = DELAY_BETWEEN_EMAILS + random.uniform(-0.8, 0.8)
        print(f" (sleep {sleep_time:.1f}s)", flush=True)
        time.sleep(sleep_time)

print("\nTrimise cu succes:", success_count)
print("Eșecuri:", fail_count)

