"""RBS REGAL — Transactional Email Service (Resend).

Single helper used across the app for one-off transactional emails:
  • Forgot-password 6-digit OTPs
  • (Future) invoice email-shares, weekly reports, etc.

Why Resend: simple HTTPS API, generous free tier (3,000/mo), great
deliverability, async-friendly. No SMTP, no IMAP, no headaches.

Config (in /app/backend/.env):
  RESEND_API_KEY      — required to actually send. If empty, the
                        helper logs the email body and returns False
                        instead of raising — useful for local dev
                        when admin hasn't signed up yet.
  RESEND_FROM_EMAIL   — sender. Default: onboarding@resend.dev (works
                        without domain verification for testing).
  RESEND_FROM_NAME    — display name. Default: "RBS REGAL".

NOTE on Resend testing-mode quirk: until the admin verifies a custom
domain at resend.com, emails will only deliver to the address used to
sign up for Resend. For production, verify your domain in the Resend
dashboard and update RESEND_FROM_EMAIL to something@yourdomain.com.
"""
import os
import asyncio
import logging
from typing import Optional

logger = logging.getLogger("rm-regal.email")


def _is_configured() -> bool:
    return bool(os.environ.get("RESEND_API_KEY", "").strip())


def _from_header() -> str:
    name = os.environ.get("RESEND_FROM_NAME", "RGE REGALGOA").strip()
    addr = os.environ.get("RESEND_FROM_EMAIL", "onboarding@resend.dev").strip()
    return f"{name} <{addr}>" if name else addr


async def send_email(to_email: str, subject: str, html: str, text: Optional[str] = None) -> bool:
    """Send a single email via Resend. Returns True on success.

    On config-missing or send failure returns False (never raises) so that
    forgot-password and other flows can degrade gracefully.
    """
    if not _is_configured():
        logger.warning(
            "RESEND_API_KEY is empty — email NOT sent to %s. Subject: %s. "
            "Admin: add RESEND_API_KEY to /app/backend/.env and restart backend.",
            to_email, subject,
        )
        return False

    try:
        import resend  # imported lazily so missing pkg doesn't break boot
        resend.api_key = os.environ["RESEND_API_KEY"].strip()
        params = {
            "from": _from_header(),
            "to": [to_email],
            "subject": subject,
            "html": html,
        }
        if text:
            params["text"] = text
        result = await asyncio.to_thread(resend.Emails.send, params)
        eid = (result or {}).get("id", "")
        logger.info("Email sent to %s (id=%s, subject=%s)", to_email, eid, subject)
        return True
    except Exception as e:
        logger.error("Resend send failed for %s: %s: %s", to_email, type(e).__name__, str(e)[:200])
        return False


# ---------- Template helpers ----------
def _otp_html(otp: str, user_name: str = "") -> str:
    """Inline-CSS table layout — battle-tested across Gmail/Outlook/Apple Mail."""
    safe_name = (user_name or "there").strip()[:60]
    return f"""<!DOCTYPE html>
<html><body style="margin:0;padding:0;background:#f6f9fc;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="background:#f6f9fc;padding:40px 20px;">
  <tr><td align="center">
    <table role="presentation" cellpadding="0" cellspacing="0" border="0" width="520" style="max-width:520px;background:#ffffff;border-radius:16px;overflow:hidden;box-shadow:0 4px 20px rgba(0,0,0,0.08);">
      <!-- Header -->
      <tr><td style="background:linear-gradient(135deg,#047857 0%,#064e3b 100%);padding:32px 32px 24px;text-align:center;">
        <div style="font-family:Georgia,'Times New Roman',serif;font-size:28px;font-weight:bold;color:#fcd34d;letter-spacing:0.5px;">RGE REGALGOA</div>
        <div style="font-size:11px;color:#a7f3d0;letter-spacing:3px;text-transform:uppercase;margin-top:4px;">ERP AI</div>
      </td></tr>
      <!-- Body -->
      <tr><td style="padding:36px 36px 24px;color:#1f2937;">
        <h1 style="margin:0 0 8px;font-size:22px;font-weight:700;color:#064e3b;">Reset Your Password</h1>
        <p style="margin:0 0 24px;font-size:14px;line-height:22px;color:#4b5563;">
          Hi {safe_name}, we received a request to reset your password. Use the 6-digit code below to continue. This code expires in <b>10 minutes</b>.
        </p>
        <!-- OTP box -->
        <div style="background:#fef3c7;border:2px dashed #f59e0b;border-radius:12px;padding:24px;text-align:center;margin:0 0 24px;">
          <div style="font-size:11px;color:#92400e;letter-spacing:2px;text-transform:uppercase;font-weight:600;margin-bottom:8px;">Your Verification Code</div>
          <div style="font-family:'Courier New',monospace;font-size:38px;font-weight:bold;color:#78350f;letter-spacing:10px;">{otp}</div>
        </div>
        <p style="margin:0 0 8px;font-size:13px;line-height:20px;color:#6b7280;">
          If you didn't request a password reset, you can safely ignore this email — your account is secure.
        </p>
        <p style="margin:16px 0 0;font-size:12px;color:#9ca3af;">
          For security, never share this code with anyone — not even RGE REGALGOA staff.
        </p>
      </td></tr>
      <!-- Footer -->
      <tr><td style="background:#f9fafb;padding:20px 36px;text-align:center;border-top:1px solid #e5e7eb;">
        <div style="font-size:11px;color:#6b7280;line-height:18px;">
          This is an automated message from RGE REGALGOA ERP AI.<br/>
          <em style="color:#92400e;">A new beginning of prosperity in business.</em><br/>
          Need help? Reply to this email or contact your administrator.
        </div>
      </td></tr>
    </table>
  </td></tr>
</table>
</body></html>"""


def _otp_text(otp: str) -> str:
    return (
        f"Your RGE REGALGOA password reset code is: {otp}\n\n"
        "This code expires in 10 minutes. If you didn't request a password reset, ignore this email.\n\n"
        "— RGE REGALGOA ERP AI\nA new beginning of prosperity in business."
    )


async def send_otp_email(to_email: str, otp: str, user_name: str = "") -> bool:
    """Sends the 6-digit OTP for forgot-password flow."""
    subject = f"Your RGE REGALGOA password reset code: {otp}"
    return await send_email(
        to_email=to_email,
        subject=subject,
        html=_otp_html(otp, user_name),
        text=_otp_text(otp),
    )
