# -*- coding: utf-8 -*-
"""
SMTP-alapú email küldés a hétfői Excel riport mellékletével.

A config.py-bol veszi a SMTP credentialst.
"""
import sys, os, smtplib, ssl, mimetypes
from email.message import EmailMessage

try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass


def send_excel_email(excel_path, date_from, date_to):
    """Elkuld egy emailt a megadott Excel csatolmannyal.

    Visszater: (success: bool, message: str)
    """
    try:
        from config import (
            SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, SMTP_USE_TLS,
            EMAIL_FELADO_CIM, EMAIL_CIMZETT
        )
        # Felado nev: az uj mezo, de ha nincs, hasznaljuk a regi FELADO_NEV-t fallback-kent
        try:
            from config import EMAIL_FELADO_NEV
        except ImportError:
            from config import FELADO_NEV as EMAIL_FELADO_NEV
    except ImportError as e:
        return False, f"Config import hiba: {e}"

    if not (SMTP_HOST and SMTP_USER and SMTP_PASSWORD and EMAIL_CIMZETT):
        return False, "SMTP adatok hianyosak a config.py-ban (SMTP_HOST/USER/PASSWORD/EMAIL_CIMZETT)"

    if not os.path.exists(excel_path):
        return False, f"Excel nem talalhato: {excel_path}"

    # Email osszeallitasa
    msg = EmailMessage()
    msg["Subject"] = f"Schneider Webshop Heti Riport — {date_from} / {date_to}"
    msg["From"] = f"{EMAIL_FELADO_NEV} <{EMAIL_FELADO_CIM or SMTP_USER}>"
    msg["To"] = EMAIL_CIMZETT

    body = (
        f"Szia Isi!\n\n"
        f"Mellékelten küldöm a heti webshop riportot a {date_from} – {date_to} időszakra.\n\n"
        f"Az élő, naponta frissülő dashboard ide kattintva érhető el:\n"
        f"https://riport.schneider-juwelier.at\n"
    )
    msg.set_content(body)

    # Excel csatolmany
    with open(excel_path, "rb") as f:
        excel_bytes = f.read()
    msg.add_attachment(
        excel_bytes,
        maintype="application",
        subtype="vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        filename=os.path.basename(excel_path),
    )

    # Kuldes
    try:
        if SMTP_USE_TLS:
            ctx = ssl.create_default_context()
            with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=30) as server:
                server.starttls(context=ctx)
                server.login(SMTP_USER, SMTP_PASSWORD)
                server.send_message(msg)
        else:
            # SSL (port 465)
            ctx = ssl.create_default_context()
            with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT, context=ctx, timeout=30) as server:
                server.login(SMTP_USER, SMTP_PASSWORD)
                server.send_message(msg)
        return True, f"Sikeresen elkuldve: {EMAIL_CIMZETT}"
    except Exception as e:
        return False, f"SMTP kuldes hiba: {e}"


if __name__ == "__main__":
    # Teszt: kuldjon el egy ures emailt a configban beallitott cimre
    import argparse
    ap = argparse.ArgumentParser()
    ap.add_argument("--excel", required=True, help="Excel fajl utvonala")
    ap.add_argument("--from-date", default="teszt-from")
    ap.add_argument("--to-date", default="teszt-to")
    args = ap.parse_args()

    ok, msg = send_excel_email(args.excel, args.from_date, args.to_date)
    print(f"{'[OK]' if ok else '[!!]'} {msg}")
    sys.exit(0 if ok else 1)
