"""HTML email templates for P2HS auth flows.

All templates use table-based layouts with fully inline styles for maximum
email client compatibility (Gmail, Outlook, Apple Mail, etc.).
Supports dark/light mode via @media (prefers-color-scheme) for compatible clients.
"""
from __future__ import annotations


# ---------------------------------------------------------------------------
# Design tokens
# ---------------------------------------------------------------------------

# Dark mode — default (inline styles, works everywhere including Outlook)
_BG = "#09090b"           # zinc-950
_CARD_BG = "#18181b"      # zinc-900
_BORDER = "#27272a"       # zinc-800
_TEXT = "#fafafa"         # white
_MUTED = "#a1a1aa"        # zinc-400
_BTN_BG = "#7c3aed"       # violet-600
_BTN_HOVER = "#6d28d9"    # violet-700 (static fallback)
_LINK = "#c084fc"         # purple-400
_FONT = "'-apple-system', 'BlinkMacSystemFont', 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif"

# Light mode overrides — applied via @media (prefers-color-scheme: light) with !important
_L_BG = "#f4f4f5"         # zinc-100
_L_CARD_BG = "#ffffff"
_L_BORDER = "#e4e4e7"     # zinc-200
_L_TEXT = "#18181b"       # zinc-900
_L_MUTED = "#52525b"      # zinc-600
_L_LINK = "#7c3aed"       # violet-600
_L_INFO_BOX = "#f4f4f5"   # zinc-100
_L_WARNING_BOX = "#fffbeb" # amber-50
_L_CODE_BG = "#f4f4f5"    # zinc-100

# Injected into <head>; !important overrides inline styles on clients that support media queries.
# Clients that don't (Outlook Windows, Gmail web) fall back to the dark inline styles.
_STYLE_BLOCK = f"""  <style>
    @media (prefers-color-scheme: light) {{
      body, .p2hs-bg {{ background-color: {_L_BG} !important; }}
      .p2hs-card {{ background-color: {_L_CARD_BG} !important; border: 1px solid {_L_BORDER} !important; }}
      .p2hs-text {{ color: {_L_TEXT} !important; }}
      .p2hs-muted {{ color: {_L_MUTED} !important; }}
      .p2hs-link {{ color: {_L_LINK} !important; }}
      .p2hs-footer {{ border-top: 1px solid {_L_BORDER} !important; }}
      .p2hs-info-box {{ background-color: {_L_INFO_BOX} !important; }}
      .p2hs-warning-box {{ background-color: {_L_WARNING_BOX} !important; }}
      .p2hs-code-block {{ background-color: {_L_CODE_BG} !important; }}
    }}
  </style>"""


def _base_wrapper(inner_html: str) -> str:
    """Wrap content in the shared outer shell (dark background, centered card)."""
    return f"""<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="color-scheme" content="light dark">
  <meta name="supported-color-schemes" content="light dark">
  <title>P2HS</title>
{_STYLE_BLOCK}
</head>
<body class="p2hs-bg" style="margin:0;padding:0;background-color:{_BG};font-family:{_FONT};">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
         class="p2hs-bg" style="background-color:{_BG};min-height:100vh;">
    <tr>
      <td align="center" style="padding:40px 16px;">

        <!-- Card -->
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
               class="p2hs-card"
               style="max-width:520px;background-color:{_CARD_BG};border-radius:12px;
                      border:1px solid {_BORDER};overflow:hidden;">

          <!-- Header bar -->
          <tr>
            <td style="background:linear-gradient(135deg,#4f1878 0%,#1e1b4b 100%);
                       padding:28px 40px 24px;">
              <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
                <tr>
                  <td>
                    <span style="font-size:22px;font-weight:700;letter-spacing:-0.5px;color:#ffffff;">
                      P2HS
                    </span>
                    <span style="font-size:11px;font-weight:500;color:#c084fc;
                                 margin-left:8px;letter-spacing:1.5px;text-transform:uppercase;">
                      Prompt to Human Scale
                    </span>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <!-- Body -->
          <tr>
            <td style="padding:36px 40px 32px;">
              {inner_html}
            </td>
          </tr>

          <!-- Footer -->
          <tr>
            <td class="p2hs-footer" style="padding:20px 40px 28px;border-top:1px solid {_BORDER};">
              <p class="p2hs-muted" style="margin:0;font-size:12px;color:{_MUTED};line-height:1.6;">
                You received this email because a sign-in was requested for your account.
                If you didn't request this, you can safely ignore this email — it will expire shortly.
              </p>
              <p style="margin:12px 0 0;font-size:12px;color:#52525b;">
                &copy; 2025 P2HS &bull;
                <a href="https://p2hs.com" style="color:#71717a;text-decoration:none;">p2hs.com</a>
              </p>
            </td>
          </tr>

        </table>
        <!-- /Card -->

      </td>
    </tr>
  </table>
</body>
</html>"""


def _cta_button(url: str, label: str) -> str:
    return f"""
    <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:28px 0 0;">
      <tr>
        <td align="center" style="border-radius:8px;background-color:{_BTN_BG};">
          <a href="{url}"
             style="display:inline-block;padding:14px 32px;font-size:15px;font-weight:600;
                    color:#ffffff;text-decoration:none;letter-spacing:0.2px;border-radius:8px;
                    background-color:{_BTN_BG};">
            {label}
          </a>
        </td>
      </tr>
    </table>"""


def _fallback_link(url: str) -> str:
    return f"""
    <p class="p2hs-muted" style="margin:20px 0 0;font-size:13px;color:{_MUTED};line-height:1.6;">
      Button not working? Copy and paste this link into your browser:
    </p>
    <p style="margin:6px 0 0;font-size:12px;word-break:break-all;">
      <a href="{url}" class="p2hs-link" style="color:{_LINK};text-decoration:none;">{url}</a>
    </p>"""


# ---------------------------------------------------------------------------
# Public builders
# ---------------------------------------------------------------------------

def build_magic_link_email(
    link_url: str,
    *,
    ttl_minutes: int = 15,
    is_signup: bool = False,
    app_name: str = "P2HS",
    logo_url: str | None = None,
    accent_color: str | None = None,
) -> tuple[str, str, str]:
    """Return (subject, html, text) for a magic-link email.

    Args:
        link_url: The full signed magic-link URL.
        ttl_minutes: Token lifetime to show in the email.
        is_signup: True for first-time signup, False for returning user login.
    """
    # Keep the historical signature for Core callers, but use the same semantic
    # presentation contract as generated applications. Signup remains a distinct
    # auth operation; its subject/copy is intentionally not a prompt fragment.
    from src.domain.email.presentation import magic_link_message, render_transactional_email

    message = magic_link_message(
        recipient="",
        app_name=app_name,
        link_url=link_url,
        ttl_minutes=ttl_minutes,
        logo_url=logo_url,
        accent_color=accent_color,
    )
    if is_signup:
        message = message.__class__(
            recipient=message.recipient,
            branding=message.branding,
            presentation=message.presentation.__class__(
                **{**message.presentation.__dict__, "title": f"Confirm your email for {message.branding.display_name}", "template_key": "auth.verify_email", "template_version": "auth.verify_email.v1", "action_label": "Confirm email"}
            ),
            subject=f"Confirm your email for {message.branding.display_name}",
            footer=message.footer,
            metadata=message.metadata,
        )
    html, text = render_transactional_email(message)
    return message.subject, html, text


def _expiry_note_days(days: int) -> str:
    label = f"{days} days" if days != 1 else "1 day"
    return f"""
    <p class="p2hs-muted" style="margin:20px 0 0;font-size:13px;color:{_MUTED};">
      This invitation expires in <strong class="p2hs-text" style="color:{_TEXT};">{label}</strong>.
    </p>"""


def build_workspace_invite_email(
    *,
    accept_landing_url: str,
    workspace_name: str,
    inviter_display: str,
    role_name: str,
    expires_days: int = 7,
) -> tuple[str, str, str]:
    """Return (subject, html, text) for a workspace invitation."""
    from src.domain.email.presentation import (
        ApplicationBranding,
        EmailMessage,
        EmailPresentation,
        render_transactional_email,
    )

    app_name = workspace_name.strip() or "Your workspace"
    days_label = f"{expires_days} days" if expires_days != 1 else "1 day"
    message = EmailMessage(
        recipient="",
        branding=ApplicationBranding(app_name),
        presentation=EmailPresentation(
            template_key="auth.invite",
            template_version="auth.invite.v1",
            title=f"You've been invited to {app_name}",
            intro=f"{inviter_display.strip() or 'A teammate'} invited you to join {app_name}.",
            action_label="Accept invitation",
            action_url=accept_landing_url,
            fallback_url=accept_landing_url,
            security_notice=f"This invitation expires in {days_label}. You must be signed in as the invited email address.",
        ),
        subject=f"You've been invited to {app_name}",
    )
    html_body, text_plain = render_transactional_email(message)
    return message.subject, html_body, text_plain


def build_billing_delegation_request_email(
    *,
    requester_display: str,
    requester_email: str,
    workspace_name: str,
    review_url: str,
) -> tuple[str, str, str]:
    """Return (subject, html, text) telling a workspace owner that a member asked to be
    allowed to put billing scopes on AI connections."""
    from src.domain.email.presentation import (
        ApplicationBranding,
        EmailMessage,
        EmailPresentation,
        render_transactional_email,
    )

    app_name = workspace_name.strip() or "Your workspace"
    who = requester_display.strip() or requester_email
    message = EmailMessage(
        recipient="",
        branding=ApplicationBranding(app_name),
        presentation=EmailPresentation(
            template_key="billing.delegation_request",
            template_version="billing.delegation_request.v1",
            title="Billing access request",
            intro=f"{who} ({requester_email.strip()}) asked to be allowed to give AI assistants access to billing in {app_name}.",
            action_label="Review request",
            action_url=review_url,
            fallback_url=review_url,
            security_notice="Approving this request does not expose saved payment details or change the member's role.",
        ),
        subject=f"{who} requested billing access in {app_name}",
    )
    html_body, text_plain = render_transactional_email(message)
    return message.subject, html_body, text_plain


# ---------------------------------------------------------------------------
# Template bodies
# ---------------------------------------------------------------------------

def build_totp_recovery_link_email(link_url: str) -> tuple[str, str, str]:
    """Return (subject, html, text) for a 2FA recovery link email."""
    inner = f"""
    <h1 class="p2hs-text" style="margin:0 0 8px;font-size:24px;font-weight:700;color:{_TEXT};letter-spacing:-0.5px;">
      Reset your two-factor authentication
    </h1>
    <p class="p2hs-muted" style="margin:0 0 24px;font-size:15px;color:{_MUTED};line-height:1.6;">
      We received a request to disable 2FA on your P2HS account. Click the button
      below to proceed. If you didn't request this, please ignore this email — your
      account remains secure.
    </p>

    {_cta_button(link_url, "Disable 2FA &amp; Sign In")}

    <table role="presentation" cellpadding="0" cellspacing="0" border="0"
           style="margin-top:20px;width:100%;">
      <tr>
        <td class="p2hs-warning-box"
            style="background-color:#0f0f17;border-radius:8px;padding:14px 16px;
                   border-left:3px solid #f59e0b;">
          <p style="margin:0;font-size:13px;line-height:1.5;">
            <strong style="color:#fbbf24;">Warning:</strong>
            <span class="p2hs-muted" style="color:{_MUTED};">
              This link disables two-factor authentication on your account. Only click it
              if you have lost access to your authenticator app.
            </span>
          </p>
        </td>
      </tr>
    </table>

    <p class="p2hs-muted" style="margin:16px 0 0;font-size:13px;color:{_MUTED};">
      This link expires in <strong class="p2hs-text" style="color:{_TEXT};">15 minutes</strong> and can only be used once.
    </p>
    {_fallback_link(link_url)}
    """
    html = _base_wrapper(inner)
    text = (
        "Reset your P2HS 2FA\n\n"
        "Use the link below to disable two-factor authentication on your account.\n\n"
        f"{link_url}\n\n"
        "This link expires in 15 minutes.\n\n"
        "If you didn't request this, ignore this email — your account is safe.\n\n"
        "— The P2HS Team\nhttps://p2hs.com"
    )
    return "Reset your P2HS two-factor authentication", html, text


def build_totp_recovery_code_email(code: str) -> tuple[str, str, str]:
    """Return (subject, html, text) for a 2FA recovery code email."""
    inner = f"""
    <h1 class="p2hs-text" style="margin:0 0 8px;font-size:24px;font-weight:700;color:{_TEXT};letter-spacing:-0.5px;">
      Your 2FA recovery code
    </h1>
    <p class="p2hs-muted" style="margin:0 0 24px;font-size:15px;color:{_MUTED};line-height:1.6;">
      Use the code below to bypass two-factor authentication and regain access to your account.
    </p>

    <!-- Code block -->
    <table role="presentation" cellpadding="0" cellspacing="0" border="0"
           style="margin:0 auto 24px;">
      <tr>
        <td align="center" class="p2hs-code-block"
            style="background-color:#0f0f17;border:2px solid {_BTN_BG};border-radius:10px;
                   padding:20px 40px;">
          <span class="p2hs-text"
                style="font-size:36px;font-weight:700;letter-spacing:10px;color:{_TEXT};
                       font-family:'Courier New',Courier,monospace;">
            {code}
          </span>
        </td>
      </tr>
    </table>

    <table role="presentation" cellpadding="0" cellspacing="0" border="0"
           style="margin-top:4px;width:100%;">
      <tr>
        <td class="p2hs-warning-box"
            style="background-color:#0f0f17;border-radius:8px;padding:14px 16px;
                   border-left:3px solid #f59e0b;">
          <p style="margin:0;font-size:13px;line-height:1.5;">
            <strong style="color:#fbbf24;">Heads up:</strong>
            <span class="p2hs-muted" style="color:{_MUTED};">
              This code will also disable your authenticator app. Set up 2FA again
              in your account settings after signing in.
            </span>
          </p>
        </td>
      </tr>
    </table>

    <p class="p2hs-muted" style="margin:16px 0 0;font-size:13px;color:{_MUTED};">
      Expires in <strong class="p2hs-text" style="color:{_TEXT};">15 minutes</strong>. Never share this code with anyone.
    </p>
    """
    html = _base_wrapper(inner)
    text = (
        "Your P2HS 2FA Recovery Code\n\n"
        f"Recovery code: {code}\n\n"
        "Enter this code to bypass 2FA and sign in. It expires in 15 minutes.\n\n"
        "This code will also disable your authenticator — re-enable 2FA after signing in.\n\n"
        "— The P2HS Team\nhttps://p2hs.com"
    )
    return "Your P2HS 2FA recovery code", html, text
