"""
Send email via SendGrid API. Used for invite links and OTP verification.
"""
import os
import logging
import html

logger = logging.getLogger(__name__)

NIXON_LOGO_URL = "https://nixonlive.com.au/wp-content/uploads/2023/07/nixon-live-logo.png"


def _sendgrid_available() -> bool:
    api_key = os.getenv("SENDGRID_API_KEY", "").strip()
    return bool(api_key)


def send_invite_email(to_email: str, invite_link: str, role_name: str) -> bool:
    """Send invite email with set-password link. Returns True if sent."""
    if not _sendgrid_available():
        logger.warning("SENDGRID_API_KEY not set; skipping invite email to %s", to_email)
        return False
    from_email = os.getenv("EMAIL_FROM", os.getenv("SENDGRID_FROM", "noreply@nixonstats.info"))
    subject = "You're invited to Nixon Performance Dashboard"
    safe_role = html.escape(role_name)
    html_content = f"""
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Invite to Nixon Performance Dashboard</title>
</head>
<body style="margin:0; padding:0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background-color: #f1f5f9; color: #334155;">
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color: #f1f5f9;">
    <tr>
      <td align="center" style="padding: 32px 16px;">
        <table role="presentation" width="100%" style="max-width: 480px; background-color: #ffffff; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.07); overflow: hidden;">
          <tr>
            <td style="padding: 32px 32px 24px; text-align: center;">
              <img src="{NIXON_LOGO_URL}" alt="Nixon" width="80" height="80" style="display: inline-block; width: 80px; height: 80px; object-fit: contain;" />
            </td>
          </tr>
          <tr>
            <td style="padding: 0 32px 24px; text-align: center;">
              <h1 style="margin: 0 0 8px; font-size: 22px; font-weight: 700; color: #0f172a;">You've been invited</h1>
              <p style="margin: 0; font-size: 15px; line-height: 1.5; color: #64748b;">You have been invited to join the <strong style="color: #0f172a;">Nixon Performance Dashboard</strong></p>
            </td>
          </tr>
          <tr>
            <td style="padding: 0 32px 24px; text-align: center;">
              <p style="margin: 0 0 20px; font-size: 14px; line-height: 1.5; color: #64748b;">Set your password to get started. This link is valid for 7 days.</p>
              <a href="{invite_link}" style="display: inline-block; padding: 14px 28px; background-color: #ea580c; color: #ffffff !important; font-size: 15px; font-weight: 600; text-decoration: none; border-radius: 8px;">Set your password</a>
            </td>
          </tr>
          <tr>
            <td style="padding: 0 32px 32px; text-align: center;">
              <p style="margin: 0; font-size: 12px; color: #94a3b8;">If you have any issues signing up, <a href="mailto:developers@nixonlive.com.au">contact the development team</a>. </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
"""
    return _send(to_email, subject, html_content.strip(), from_email)


def send_reset_password_email(to_email: str, reset_link: str) -> bool:
    """Send password reset email with link to reset-password page. Returns True if sent."""
    if not _sendgrid_available():
        logger.warning("SENDGRID_API_KEY not set; skipping reset email to %s", to_email)
        return False
    from_email = os.getenv("EMAIL_FROM", os.getenv("SENDGRID_FROM", "noreply@nixonstats.info"))
    subject = "Reset your Nixon Performance Dashboard password"
    html_content = f"""
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Reset your password</title>
</head>
<body style="margin:0; padding:0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background-color: #f1f5f9; color: #334155;">
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color: #f1f5f9;">
    <tr>
      <td align="center" style="padding: 32px 16px;">
        <table role="presentation" width="100%" style="max-width: 480px; background-color: #ffffff; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.07); overflow: hidden;">
          <tr>
            <td style="padding: 32px 32px 24px; text-align: center;">
              <img src="{NIXON_LOGO_URL}" alt="Nixon" width="80" height="80" style="display: inline-block; width: 80px; height: 80px; object-fit: contain;" />
            </td>
          </tr>
          <tr>
            <td style="padding: 0 32px 24px; text-align: center;">
              <h1 style="margin: 0 0 8px; font-size: 22px; font-weight: 700; color: #0f172a;">Reset your password</h1>
              <p style="margin: 0; font-size: 15px; line-height: 1.5; color: #64748b;">You requested to reset your password for the <strong style="color: #0f172a;">Nixon Performance Dashboard</strong></p>
            </td>
          </tr>
          <tr>
            <td style="padding: 0 32px 24px; text-align: center;">
              <p style="margin: 0 0 20px; font-size: 14px; line-height: 1.5; color: #64748b;">Click the link below to set a new password. This link is valid for 1 hour.</p>
              <a href="{reset_link}" style="display: inline-block; padding: 14px 28px; background-color: #ea580c; color: #ffffff !important; font-size: 15px; font-weight: 600; text-decoration: none; border-radius: 8px;">Reset your password</a>
            </td>
          </tr>
          <tr>
            <td style="padding: 0 32px 32px; text-align: center;">
              <p style="margin: 0; font-size: 12px; color: #94a3b8;">If you didn't request this, you can safely ignore this email. Your password will remain unchanged.</p>
              <p style="margin: 8px 0 0; font-size: 12px; color: #94a3b8;">If you have any issues, <a href="mailto:developers@nixonlive.com.au">contact the development team</a>.</p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
"""
    return _send(to_email, subject, html_content.strip(), from_email)


def send_otp_email(to_email: str, code: str) -> bool:
    """Send 6-digit OTP for re-verification. Returns True if sent."""
    if not _sendgrid_available():
        logger.warning("SENDGRID_API_KEY not set; skipping OTP email to %s", to_email)
        return False
    from_email = os.getenv("EMAIL_FROM", os.getenv("SENDGRID_FROM", "noreply@nixonstats.info"))
    subject = "Your Nixon Dashboard verification code"
    html = f"""
    <p>Your verification code is: <strong>{code}</strong></p>
    <p>Enter this code in the dashboard to continue. It expires in 10 minutes.</p>
    <p>If you didn't request this, you can ignore this email.</p>
    """
    return _send(to_email, subject, html, from_email)


def _send(to_email: str, subject: str, html_content: str, from_email: str) -> bool:
    try:
        from sendgrid import SendGridAPIClient
        from sendgrid.helpers.mail import Mail

        message = Mail(
            from_email=from_email,
            to_emails=to_email,
            subject=subject,
            html_content=html_content,
        )
        sg = SendGridAPIClient(os.getenv("SENDGRID_API_KEY"))
        sg.send(message)
        logger.info("Email sent to %s: %s", to_email, subject)
        return True
    except Exception as e:
        logger.exception("SendGrid send failed to %s: %s", to_email, e)
        return False
