from scaleway import Client
from scaleway.tem.v1alpha1.api import TemV1Alpha1API
from scaleway.tem.v1alpha1.types import CreateEmailRequestAddress
from html2text import HTML2Text
from flask import current_app


def send_email(to_email, to_name, subject, html):
    access_key = current_app.config['SW_EMAIL_ACCESS_KEY']
    secret_key = current_app.config['SW_EMAIL_SECRET_KEY']
    default_project_id = current_app.config['SW_PROJECT']
    default_region = "fr-par"
    client = Client(
        access_key=access_key,
        secret_key=secret_key,
        default_project_id=default_project_id,
        default_region=default_region
    )
    tem = TemV1Alpha1API(client)
    from_ = CreateEmailRequestAddress(email=current_app.config['SW_EMAIL_SENDER'],
                                      name=current_app.config['SW_EMAIL_NAME'])
    to_ = CreateEmailRequestAddress(email=to_email, name=to_name)

    email = tem.create_email(
        from_=from_,
        to=[to_],
        subject=subject,
        text=html_to_text(html),
        html=html,
        project_id=default_project_id,
    )


def html_to_text(html_content):
    """Convert HTML to plain text using html2text"""
    h = HTML2Text()
    h.ignore_images = True
    h.ignore_emphasis = False
    h.body_width = 0  # No wrapping
    return h.handle(html_content)
