# send_mail.py
import smtplib
from email.message import EmailMessage
import time
import schedule
import os
import mimetypes
import urllib.parse
import html
from pathlib import Path
from datetime import datetime

# ========= Config =========
SENDER = "Mini.Mo.KI.System@gmail.com"
RECIPIENTS = [
    "m.almoazen@estador.de",
    "r.scheckel@estador.de"
]
APP_PASSWORD = "ftousflzzcnzqzes"  # For production, use an env var
REPORTS_DIR = str(Path(__file__).resolve().parent / "reports_2025")

# If you host reports_2025 on the web, set BASE_URL so links work for everyone:
# Example: BASE_URL = "https://abdalrahman.de/reports_2025"
BASE_URL = None  # ← set to your public URL or keep None

# If not hosted, but you open the email on the same machine in a desktop client,
# you can enable local file links (works only locally, not in webmail):
LOCAL_LINKS = True  # file:///C:/... links (desktop clients only)
# ==========================


def get_latest_file(folder: str) -> str | None:
    """
    Returns the newest file (by modification time) inside 'folder',
    or None if there is no file.
    """
    if not os.path.isdir(folder):
        return None

    files = [
        os.path.join(folder, f)
        for f in os.listdir(folder)
        if os.path.isfile(os.path.join(folder, f))
    ]

    if not files:
        return None

    return max(files, key=os.path.getmtime)


def build_single_file_html(latest_file: str | None,
                           base_url: str | None,
                           local_links: bool) -> str:
    """
    Creates an HTML list (<ul>) containing only the newest file.
    If no file exists, returns a 'no file' message.
    """
    if not latest_file:
        return "<p style='margin:0;'>— keine Datei gefunden —</p>"

    file_name = os.path.basename(latest_file)
    size_mb = os.path.getsize(latest_file) / (1024 * 1024)
    size_str = f"{size_mb:.2f} MB"

    href = None
    if base_url:
        href = base_url.rstrip("/") + "/" + urllib.parse.quote(file_name) + "?download=1"
    elif local_links:
        abs_path = os.path.abspath(latest_file).replace("\\", "/")
        href = "file:///" + abs_path

    safe_name = html.escape(file_name)

    if href:
        return (
            "<ul style='margin:0; padding-left:20px;'>"
            f"<li><a href=\"{href}\">{safe_name}</a> "
            f"<span style='color:#888;'>({size_str})</span></li>"
            "</ul>"
        )
    else:
        return (
            "<ul style='margin:0; padding-left:20px;'>"
            f"<li>{safe_name} <span style='color:#888;'>({size_str})</span></li>"
            "</ul>"
        )


def read_file_content(latest_file: str | None) -> str:
    """
    Reads the full text content of the latest report file.
    Returns an empty string if no file exists or reading fails.
    """
    if not latest_file:
        return ""

    try:
        # Annahme: Textdatei / UTF-8
        with open(latest_file, "r", encoding="utf-8", errors="replace") as f:
            content = f.read()
        return content
    except Exception as e:
        # Fallback – im E-Mail-Body einen Hinweis ausgeben
        return f"Fehler beim Lesen der Datei: {e}"


def send_report():
    # Determine newest file in the reports directory
    latest_file = get_latest_file(REPORTS_DIR)

    # Build HTML list with only the newest file
    files_html = build_single_file_html(latest_file, base_url=BASE_URL, local_links=LOCAL_LINKS)

    # Read content (summary etc.) from the newest file
    report_text = read_file_content(latest_file)
    # HTML-escapen, damit Sonderzeichen korrekt angezeigt werden
    safe_report_text = html.escape(report_text) if report_text else "— Kein Inhalt verfügbar —"


    msg = EmailMessage()
    msg["From"] = SENDER
    msg["To"] = ", ".join(RECIPIENTS)
    msg["Subject"] = "KI System Updater!"
    msg.set_content("This is an HTML email. Please use an email client that supports HTML.")

    html_body = f"""
        <!DOCTYPE html>
        <html>
        <body style="font-family: Arial, sans-serif; background-color:#f4f4f4; padding:20px;">
            <div style="max-width:600px; margin:auto; background:#fff; border-radius:8px; overflow:hidden; box-shadow:0 2px 8px rgba(0,0,0,0.1);">
            
            <!-- HEADER -->
            <div style="background:#007BFF; color:#fff; padding:20px; text-align:center;">
                <h1 style="margin:0; font-size:28px;">Welcome to Python Mailer</h1>
            </div>
            
            <!-- MAIN CONTENT -->
            <div style="padding:20px; color:#333;">
                <h2 style="color:#007BFF;">Hallo 👋</h2>
                <p style="font-size:16px; line-height:1.6; margin-bottom:24px;">
                Dies ist eine <b>automatisch generierte E-Mail</b>, gesendet von 
                <span style="color:#007BFF;">Python</span> über Personal KI System. Arbeit Zeit 24/7.
                </p>

                <h3 style="margin:24px 0 8px;">📄 Verfügbare Datei (neuester Report in reports_2025)</h3>
                <p style="margin:0 0 16px; font-size:14px; color:#666;">
                Klicken Sie auf die Datei, um sie herunterzuladen.
                </p>
                {files_html}

                <h3 style="margin:32px 0 8px;">🧾 Zusammenfassung aus der Datei</h3>
                <p style="margin:0 0 8px; font-size:14px; color:#666;">
                Unten sehen Sie den Inhalt / die Kurz-Zusammenfassung aus dem aktuellen Report:
                </p>
                <pre style="background:#f7f7f7; padding:12px; border-radius:6px; font-size:13px; line-height:1.4; overflow-x:auto; white-space:pre-wrap; border:1px solid #e0e0e0;">
        {safe_report_text}
                </pre>

                <!-- BUTTON AT THE BOTTOM OF CONTENT -->
                <div style="margin-top:32px; margin-bottom:20px; text-align:center;">
                <a href="https://business.facebook.com/" 
                    style="background:#1877f2; color:#fff; padding:14px 28px; text-decoration:none; border-radius:5px; font-size:16px; display:inline-block;">
                    📘 Kontrollieren Sie unsere Facebook Marketing-Seite
                </a>
                </div>
            </div>
            
            <!-- BOT INFORMATION -->
            <div style="padding:20px; border-top:1px solid #ddd; font-size:14px; color:#555;">
                <h3 style="margin-bottom:8px; color:#333;">ℹ️ Bot-Informationen</h3>
                <p style="margin:4px 0;">ID: <b>KI-System-34501</b></p>
                <p style="margin:4px 0;">Aufgabe: <b>Meta Marketing Optimizer</b></p>
                <p style="margin:4px 0;">Firma: <b>Estador GmbH</b></p>
                <p style="margin:4px 0;">Entwicklungsanfragen: <a href="mailto:m.almoazen@estador.de">m.almoazen@estador.de</a></p>
                <p style="margin:4px 0;">Erstellungsdatum: <b>15.10.2025</b></p>
                <p style="margin:4px 0;">IQ: <b>35</b></p>
                <p style="margin:4px 0;">Access Power: <b>10</b></p>
                <p style="margin:4px 0;">Version: <b>V.0.1</b></p>
            </div>
            
            <!-- FOOTER -->
            <div style="background:#f1f1f1; padding:15px; text-align:center; font-size:12px; color:#555;">
                © 2025 Estador GmbH – Alle Rechte vorbehalten.
            </div>
            
            </div>
        </body>
        </html>
        """
    msg.add_alternative(html_body, subtype="html")


    # Attach only the newest file as a fallback for download
    if latest_file:
        ctype, _ = mimetypes.guess_type(latest_file)
        maintype, subtype = (ctype or "application/octet-stream").split("/", 1)

        with open(latest_file, "rb") as f:
            msg.add_attachment(
                f.read(),
                maintype=maintype,
                subtype=subtype,
                filename=os.path.basename(latest_file)
            )
    with smtplib.SMTP("smtp.gmail.com", 587, timeout=30) as smtp:
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        smtp.login(SENDER, APP_PASSWORD)
        smtp.send_message(msg, to_addrs=RECIPIENTS)

    print("✅ Email sent with newest report + summary + attachment.")


# ============= Schedule =============
# Set your desired time (24h format, local)
schedule.every().day.at("08:30").do(send_report)

print("⏳ Scheduler running. First call now for testing...")

while True:
    schedule.run_pending()
    time.sleep(10)
