"""
Email sending for verification and password-reset links.

Configured via environment variables; if SMTP isn't set, it falls back to printing
the email to the server console (handy for local testing — you'll see the link).

  SMTP_HOST, SMTP_PORT (default 587), SMTP_USER, SMTP_PASS, SMTP_FROM, SMTP_TLS (1/0)

For production use your mail provider's SMTP (e.g. Gmail Workspace, SendGrid,
Mailgun, Postmark, or your cPanel mail account).
"""

from __future__ import annotations

import os
import smtplib
from email.message import EmailMessage


def send_email(to: str, subject: str, body: str) -> bool:
    host = os.environ.get("SMTP_HOST")
    sender = os.environ.get("SMTP_FROM", os.environ.get("SMTP_USER", "no-reply@biosync-lab.co.za"))
    if not host:
        print(f"\n[email:console-fallback] to={to}\nSubject: {subject}\n\n{body}\n")
        return False
    msg = EmailMessage()
    msg["From"] = sender
    msg["To"] = to
    msg["Subject"] = subject
    msg.set_content(body)
    try:
        port = int(os.environ.get("SMTP_PORT", "587"))
        with smtplib.SMTP(host, port, timeout=20) as s:
            if os.environ.get("SMTP_TLS", "1") == "1":
                s.starttls()
            user = os.environ.get("SMTP_USER")
            if user:
                s.login(user, os.environ.get("SMTP_PASS", ""))
            s.send_message(msg)
        return True
    except Exception as e:
        print(f"[email] send failed: {e}")
        return False


def portal_url() -> str:
    return os.environ.get("PORTAL_URL", "http://127.0.0.1:8090").rstrip("/")
