import email.policy
import django
from django.conf import settings


settings.configure(DEBUG=True, SECRET_KEY="poc-only", ROOT_URLCONF="urls_stub",
                   EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend")
django.setup()


from django.core.mail import EmailMessage, send_mail
from django.core.validators import URLValidator, validate_domain_name, validate_email


SEP = "\u2028" # LINE SEPARATOR (category Zl)


for v in [
    f"user@example{SEP}.com",
    "user@example\u2029.com", # PARAGRAPH SEPARATOR (Zp)
    "user@exa\u1680mple.com", # OGHAM SPACE MARK (Zs)
    "user@exa\u2000mple.com", # EN QUAD (Zs)
    "user@example\u3000.com", # IDEOGRAPHIC SPACE (Zs)
    "user@example\ufeff.com", # ZERO WIDTH NO-BREAK SPACE (Cf)
]:
    try:
        validate_email(v)
        print(f"EmailValidator ACCEPT {v!r}")
    except Exception:
        print(f"EmailValidator reject {v!r}")


for d in ["example\u2028.com", "example\u2029.com", "exa\u1680mple.com"]:
    try:
        validate_domain_name(d)
        print(f"DomainNameValidator ACCEPT {d!r}")
    except Exception:
        print(f"DomainNameValidator reject {d!r}")


uv = URLValidator()
for u in ["http://example\u2028.com/", "http://exa\u1680mple.com/"]:
    try:
        uv(u)
        print(f"URLValidator ACCEPT {u!r}")
    except Exception:
        print(f"URLValidator reject {u!r}")


print("splitlines:", "a\u2028b".splitlines())


addr = f"user@example{SEP}.com"
for pol in (None, email.policy.SMTP):
    m = EmailMessage(subject="s", body="b", to=[addr])
    try:
        m.message(policy=pol)
        print(f"message(policy={pol!r}): built OK")
    except Exception as e:
        print(f"message(policy={pol!r}) -> {type(e).__name__}: {e}")


try:
    send_mail("s", "b", "from@example.com", [addr])
    print("send_mail(): sent OK")
except Exception as e:
    print(f"send_mail() -> {type(e).__name__}: {e}")


from django.core.mail.backends.smtp import EmailBackend
be = EmailBackend.__new__(EmailBackend)
print("prep_address(%r) = %r" % (addr, be.prep_address(addr)))
