"""
email_service.py
------------------
Email verification is a required feature, but this sandbox/build stage has
no SMTP credentials or outbound network access configured. This module
implements the FULL logic (token generation, expiry, verification link
construction) and a pluggable `send()` step:

  * If EMAIL_SENDING_ENABLED=true and SMTP_* env vars are set, it sends a
    real email via smtplib.
  * Otherwise, it logs the verification link to the console/log — enough to
    test the flow end-to-end in development without a mail server.
"""

import logging
import secrets
import smtplib
from email.mime.text import MIMEText

from ..config import settings

logger = logging.getLogger("mindscreen.email")


def generate_verification_token() -> str:
    return secrets.token_urlsafe(32)


def build_verification_link(token: str) -> str:
    return f"{settings.APP_BASE_URL}/auth/verify-email?token={token}"


def send_verification_email(to_email: str, token: str) -> None:
    link = build_verification_link(token)
    subject = "Verify your MindScreen AI research account"
    body = (
        f"Hi,\n\nPlease verify your email for MindScreen AI by visiting:\n{link}\n\n"
        "This link is used only to confirm your email address for the research "
        "study. If you didn't request this, you can ignore this email.\n"
    )

    if not settings.EMAIL_SENDING_ENABLED:
        logger.info("[DEV MODE — no SMTP configured] Verification email for %s: %s", to_email, link)
        return

    msg = MIMEText(body)
    msg["Subject"] = subject
    msg["From"] = settings.SMTP_USER
    msg["To"] = to_email

    with smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT) as server:
        server.starttls()
        server.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
        server.send_message(msg)
