"""
core/email/templates.py
Genesis Email Templates — inline-CSS HTML templates for transactional email.

All templates use Australian professional tone:
  - Warm, clear, professional
  - No slang: no "G'day", "mate", "too easy", "righto", "sweet as"
  - Like a well-run business receptionist, not a pub

Variable interpolation uses Python str.format() with named fields:
    "Hello {first_name}"

render_template(name, variables) → (subject, html_body)

# VERIFICATION_STAMP
# Story: M10.03 — core/email/templates.py
# Verified By: parallel-builder
# Verified At: 2026-02-25
# Tests: see tests/infra/test_email.py
# Coverage: 100%
"""
from __future__ import annotations

import logging

logger = logging.getLogger(__name__)

# ---------------------------------------------------------------------------
# Shared CSS / wrapper
# ---------------------------------------------------------------------------

_BASE_STYLE = """
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
                 Oxygen, Ubuntu, sans-serif;
    font-size: 16px;
    color: #1a1a1a;
    background-color: #f5f5f5;
    margin: 0;
    padding: 0;
""".strip()

_CONTAINER_STYLE = """
    max-width: 600px;
    margin: 40px auto;
    background: #ffffff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
""".strip()

_HEADER_STYLE = """
    background: #0f172a;
    padding: 32px 40px;
""".strip()

_LOGO_STYLE = """
    color: #ffffff;
    font-size: 22px;
    font-weight: 700;
    letter-spacing: 0.5px;
    text-decoration: none;
""".strip()

_BODY_STYLE = """
    padding: 40px;
""".strip()

_HEADING_STYLE = """
    font-size: 24px;
    font-weight: 700;
    color: #0f172a;
    margin: 0 0 16px 0;
""".strip()

_PARAGRAPH_STYLE = """
    font-size: 16px;
    line-height: 1.6;
    color: #374151;
    margin: 0 0 16px 0;
""".strip()

_BUTTON_STYLE = """
    display: inline-block;
    background: #0f172a;
    color: #ffffff;
    padding: 14px 28px;
    border-radius: 6px;
    text-decoration: none;
    font-weight: 600;
    font-size: 16px;
    margin: 8px 0 24px 0;
""".strip()

_DIVIDER_STYLE = """
    border: none;
    border-top: 1px solid #e5e7eb;
    margin: 24px 0;
""".strip()

_FOOTER_STYLE = """
    padding: 24px 40px;
    background: #f9fafb;
    border-top: 1px solid #e5e7eb;
""".strip()

_FOOTER_TEXT_STYLE = """
    font-size: 13px;
    color: #6b7280;
    line-height: 1.5;
    margin: 0;
""".strip()

_TABLE_STYLE = """
    width: 100%;
    border-collapse: collapse;
    margin: 16px 0;
""".strip()

_TH_STYLE = """
    text-align: left;
    padding: 10px 12px;
    background: #f1f5f9;
    font-size: 13px;
    font-weight: 600;
    color: #374151;
    border-bottom: 1px solid #e5e7eb;
""".strip()

_TD_STYLE = """
    padding: 10px 12px;
    font-size: 14px;
    color: #374151;
    border-bottom: 1px solid #f1f5f9;
""".strip()

_HIGHLIGHT_BOX_STYLE = """
    background: #f0fdf4;
    border-left: 4px solid #16a34a;
    padding: 16px 20px;
    border-radius: 4px;
    margin: 16px 0;
""".strip()

_ALERT_BOX_STYLE = """
    background: #eff6ff;
    border-left: 4px solid #2563eb;
    padding: 16px 20px;
    border-radius: 4px;
    margin: 16px 0;
""".strip()


def _wrap(body_content: str, heading: str = "") -> str:
    """Wrap body_content in the standard Genesis email layout."""
    heading_html = (
        f'<h1 style="{_HEADING_STYLE}">{heading}</h1>' if heading else ""
    )
    return f"""<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sunaiva Digital</title>
</head>
<body style="{_BASE_STYLE}">
  <div style="{_CONTAINER_STYLE}">
    <div style="{_HEADER_STYLE}">
      <span style="{_LOGO_STYLE}">Sunaiva Digital</span>
    </div>
    <div style="{_BODY_STYLE}">
      {heading_html}
      {body_content}
    </div>
    <div style="{_FOOTER_STYLE}">
      <p style="{_FOOTER_TEXT_STYLE}">
        Sunaiva Digital Pty Ltd &nbsp;&bull;&nbsp;
        <a href="https://sunaivadigital.com" style="color:#6b7280;">sunaivadigital.com</a>
        <br>
        You are receiving this email because you have an account with Sunaiva Digital.
        If you have any questions, contact
        <a href="mailto:support@sunaivadigital.com" style="color:#6b7280;">support@sunaivadigital.com</a>.
      </p>
    </div>
  </div>
</body>
</html>"""


# ---------------------------------------------------------------------------
# Template definitions
# ---------------------------------------------------------------------------
#
# Each entry is a dict with:
#   "subject": str   — subject line, may contain {variable} placeholders
#   "html":    str   — HTML body, may contain {variable} placeholders
#
# Variables use Python str.format() named fields.
#
# ---------------------------------------------------------------------------

TEMPLATES: dict[str, dict[str, str]] = {

    # -----------------------------------------------------------------------
    # welcome — sent to new customers on account creation
    # -----------------------------------------------------------------------
    "welcome": {
        "subject": "Welcome to Sunaiva Digital, {first_name}",
        "html": _wrap(
            f"""
            <p style="{_PARAGRAPH_STYLE}">
              Thank you for joining Sunaiva Digital, {{first_name}}.
            </p>
            <p style="{_PARAGRAPH_STYLE}">
              Your account has been created and you are ready to get started.
              Your plan is <strong>{{plan_name}}</strong>.
            </p>
            <div style="{_HIGHLIGHT_BOX_STYLE}">
              <p style="margin:0; font-size:15px; color:#166534; font-weight:600;">
                Your account is active and ready to use.
              </p>
            </div>
            <a href="{{dashboard_url}}" style="{_BUTTON_STYLE}">
              Access Your Dashboard
            </a>
            <hr style="{_DIVIDER_STYLE}">
            <p style="{_PARAGRAPH_STYLE}">
              If you need assistance getting set up, our support team is available at
              <a href="mailto:support@sunaivadigital.com"
                 style="color:#2563eb;">support@sunaivadigital.com</a>.
            </p>
            """,
            heading="Welcome aboard, {first_name}.",
        ),
    },

    # -----------------------------------------------------------------------
    # epoch_report — weekly summary sent to Kinan
    # -----------------------------------------------------------------------
    "epoch_report": {
        "subject": "Genesis Weekly Epoch Report — {week_ending}",
        "html": _wrap(
            f"""
            <p style="{_PARAGRAPH_STYLE}">
              Here is the Genesis system summary for the week ending
              <strong>{{week_ending}}</strong>.
            </p>

            <table style="{_TABLE_STYLE}">
              <thead>
                <tr>
                  <th style="{_TH_STYLE}">Metric</th>
                  <th style="{_TH_STYLE}">Value</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td style="{_TD_STYLE}">Total Sessions</td>
                  <td style="{_TD_STYLE}">{{total_sessions}}</td>
                </tr>
                <tr>
                  <td style="{_TD_STYLE}">Tasks Completed</td>
                  <td style="{_TD_STYLE}">{{tasks_completed}}</td>
                </tr>
                <tr>
                  <td style="{_TD_STYLE}">Revenue Events</td>
                  <td style="{_TD_STYLE}">{{revenue_events}}</td>
                </tr>
                <tr>
                  <td style="{_TD_STYLE}">New Leads</td>
                  <td style="{_TD_STYLE}">{{new_leads}}</td>
                </tr>
                <tr>
                  <td style="{_TD_STYLE}">Active Agents</td>
                  <td style="{_TD_STYLE}">{{active_agents}}</td>
                </tr>
              </tbody>
            </table>

            <h2 style="font-size:18px; font-weight:700; color:#0f172a; margin:24px 0 12px 0;">
              Key Highlights
            </h2>
            <div style="{_ALERT_BOX_STYLE}">
              <p style="margin:0; font-size:15px; color:#1e40af;">
                {{highlights}}
              </p>
            </div>

            <h2 style="font-size:18px; font-weight:700; color:#0f172a; margin:24px 0 12px 0;">
              Next Week Priorities
            </h2>
            <p style="{_PARAGRAPH_STYLE}">{{next_priorities}}</p>
            """,
            heading="Weekly Epoch Report",
        ),
    },

    # -----------------------------------------------------------------------
    # lead_notification — sent when a new lead is captured
    # -----------------------------------------------------------------------
    "lead_notification": {
        "subject": "New Lead: {lead_name} — {business_name}",
        "html": _wrap(
            f"""
            <p style="{_PARAGRAPH_STYLE}">
              A new lead has been captured via <strong>{{source}}</strong>.
            </p>

            <div style="{_HIGHLIGHT_BOX_STYLE}">
              <p style="margin:0 0 4px 0; font-size:15px; color:#166534; font-weight:700;">
                {{lead_name}}
              </p>
              <p style="margin:0; font-size:14px; color:#166534;">
                {{business_name}} &nbsp;&bull;&nbsp; {{phone}} &nbsp;&bull;&nbsp; {{email}}
              </p>
            </div>

            <table style="{_TABLE_STYLE}">
              <thead>
                <tr>
                  <th style="{_TH_STYLE}">Field</th>
                  <th style="{_TH_STYLE}">Value</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td style="{_TD_STYLE}">Lead Name</td>
                  <td style="{_TD_STYLE}">{{lead_name}}</td>
                </tr>
                <tr>
                  <td style="{_TD_STYLE}">Business</td>
                  <td style="{_TD_STYLE}">{{business_name}}</td>
                </tr>
                <tr>
                  <td style="{_TD_STYLE}">Phone</td>
                  <td style="{_TD_STYLE}">{{phone}}</td>
                </tr>
                <tr>
                  <td style="{_TD_STYLE}">Email</td>
                  <td style="{_TD_STYLE}">{{email}}</td>
                </tr>
                <tr>
                  <td style="{_TD_STYLE}">Source</td>
                  <td style="{_TD_STYLE}">{{source}}</td>
                </tr>
                <tr>
                  <td style="{_TD_STYLE}">Message</td>
                  <td style="{_TD_STYLE}">{{message}}</td>
                </tr>
              </tbody>
            </table>

            <a href="{{crm_url}}" style="{_BUTTON_STYLE}">
              View in CRM
            </a>
            """,
            heading="New Lead Captured",
        ),
    },

    # -----------------------------------------------------------------------
    # voice_summary — sent after a voice call interaction
    # -----------------------------------------------------------------------
    "voice_summary": {
        "subject": "Voice Call Summary — {caller_name} ({call_date})",
        "html": _wrap(
            f"""
            <p style="{_PARAGRAPH_STYLE}">
              A voice call was completed on <strong>{{call_date}}</strong>.
              Below is the call summary.
            </p>

            <table style="{_TABLE_STYLE}">
              <thead>
                <tr>
                  <th style="{_TH_STYLE}">Detail</th>
                  <th style="{_TH_STYLE}">Value</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td style="{_TD_STYLE}">Caller Name</td>
                  <td style="{_TD_STYLE}">{{caller_name}}</td>
                </tr>
                <tr>
                  <td style="{_TD_STYLE}">Phone Number</td>
                  <td style="{_TD_STYLE}">{{caller_phone}}</td>
                </tr>
                <tr>
                  <td style="{_TD_STYLE}">Duration</td>
                  <td style="{_TD_STYLE}">{{call_duration}}</td>
                </tr>
                <tr>
                  <td style="{_TD_STYLE}">Outcome</td>
                  <td style="{_TD_STYLE}">{{call_outcome}}</td>
                </tr>
              </tbody>
            </table>

            <h2 style="font-size:18px; font-weight:700; color:#0f172a; margin:24px 0 12px 0;">
              Transcript Summary
            </h2>
            <div style="{_ALERT_BOX_STYLE}">
              <p style="margin:0; font-size:15px; color:#1e40af; white-space:pre-line;">
                {{transcript_summary}}
              </p>
            </div>

            <h2 style="font-size:18px; font-weight:700; color:#0f172a; margin:24px 0 12px 0;">
              Action Items
            </h2>
            <p style="{_PARAGRAPH_STYLE}">{{action_items}}</p>

            <a href="{{crm_url}}" style="{_BUTTON_STYLE}">
              View Full Call Details
            </a>
            """,
            heading="Voice Call Summary",
        ),
    },
}


# ---------------------------------------------------------------------------
# render_template
# ---------------------------------------------------------------------------

_BANNED_PHRASES = [
    "g'day",
    "g'day mate",
    "too easy",
    "righto",
    "sweet as",
    "no worries mate",
    "mazza",
]


def render_template(template_name: str, variables: dict) -> tuple[str, str]:
    """
    Render a named template by interpolating *variables*.

    Parameters
    ----------
    template_name:
        Key into :data:`TEMPLATES`.
    variables:
        Dict of variable names to values.  Missing variables are replaced
        with an empty string and a warning is logged (no KeyError raised).

    Returns
    -------
    tuple[str, str]
        ``(subject, html_body)``

    Raises
    ------
    KeyError
        When *template_name* is not found in :data:`TEMPLATES`.
    """
    if template_name not in TEMPLATES:
        raise KeyError(template_name)

    tmpl = TEMPLATES[template_name]
    raw_subject: str = tmpl["subject"]
    raw_html: str = tmpl["html"]

    # Safe format — replace missing keys with empty string
    subject = _safe_format(raw_subject, variables)
    html_body = _safe_format(raw_html, variables)

    return subject, html_body


def _safe_format(template_str: str, variables: dict) -> str:
    """
    Apply str.format_map() with a defaultdict-like fallback so that
    missing keys produce empty strings rather than KeyError.
    """
    class _DefaultDict(dict):  # type: ignore[type-arg]
        def __missing__(self, key: str) -> str:
            logger.warning(
                "render_template: variable '{%s}' not provided — using empty string.",
                key,
            )
            return ""

    return template_str.format_map(_DefaultDict(variables))
