"""Email OTP tool — reusable by any project (TA-ATS, DEMO, Demo3...).
SMTP credentials live in the MCP server's .env (one place).
In dev (no SMTP configured), the OTP is printed to the MCP console.
"""
import os
import random
import smtplib
from email.mime.text import MIMEText


def send_email_otp(email: str) -> dict:
    """Generate a 6-digit OTP, email it, and return the OTP to the caller.

    The calling project stores the returned OTP in its own database and
    verifies it later. The MCP server keeps no state.
    """
    otp = f"{random.randint(100000, 999999)}"
    expiry = os.getenv("OTP_EXPIRY_MINUTES", "5")
    body = f"Your verification code is {otp}. It expires in {expiry} minutes."

    host = os.getenv("EMAIL_HOST", "")
    user = os.getenv("EMAIL_HOST_USER", "")
    password = os.getenv("EMAIL_HOST_PASSWORD", "")
    sender = os.getenv("DEFAULT_FROM_EMAIL", "no-reply@ta-ats.local")

    if host and user and password:
        msg = MIMEText(body)
        msg["Subject"] = "Your verification code"
        msg["From"] = sender
        msg["To"] = email
        with smtplib.SMTP(host, int(os.getenv("EMAIL_PORT", "587"))) as s:
            if os.getenv("EMAIL_USE_TLS", "true").lower() == "true":
                s.starttls()
            s.login(user, password)
            s.sendmail(sender, [email], msg.as_string())
        sent = True
    else:
        # dev: no SMTP -> print to MCP console
        print(f"[MCP EMAIL OTP] to {email}: {otp}")
        sent = False

    return {"otp": otp, "sent": sent}
