"""
Site Templates Seeder — PRD-010

Inserts all 28 platform-level templates into `site_templates`.
Uses INSERT ... ON CONFLICT (template_key) DO NOTHING so the seeder is
idempotent and safe to re-run at any time.

Usage
-----
Standalone (from repo root with venv activated):
    python -m src.apps.site_templates.seeder

Importable:
    from src.apps.site_templates.seeder import seed
    seed(db)
"""

from __future__ import annotations

import json
import logging
from typing import List

from sqlalchemy import text
from sqlalchemy.orm import Session

logger = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def _row(
    template_key: str,
    template_name: str,
    description: str,
    channel: str,
    template_type: str,
    subject: str | None,
    body_html: str | None,
    body_text: str | None,
    variables: List[str],
    primary_color: str = "#28B4ED",
    accent_color: str = "#FB7585",
    text_color: str = "#252525",
) -> dict:
    return {
        "template_key": template_key,
        "template_name": template_name,
        "description": description,
        "channel": channel,
        "template_type": template_type,
        "subject": subject,
        "body_html": body_html,
        "body_text": body_text,
        "primary_color": primary_color,
        "accent_color": accent_color,
        "text_color": text_color,
        "variables": json.dumps(variables),
        "is_active": True,
    }


# ---------------------------------------------------------------------------
# Auth platform-branded HTML wrapper
# (no {{ primary_color }} / {{ accent_color }} — fixed HubWallet branding)
# ---------------------------------------------------------------------------

_AUTH_HTML_WRAPPER = """\
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{title}</title>
<style>
  body {{ margin:0; padding:0; background:#F4F7FA; font-family:'Inter',Arial,sans-serif; color:#252525; }}
  .outer {{ width:100%; background:#F4F7FA; padding:40px 0; }}
  .card  {{ max-width:560px; margin:0 auto; background:#FFFFFF;
            border-radius:8px; overflow:hidden;
            box-shadow:0 2px 8px rgba(0,0,0,.08); }}
  .header {{ background:#28B4ED; padding:28px 32px; text-align:center; }}
  .header h1 {{ margin:0; color:#FFFFFF; font-size:22px; font-weight:700; letter-spacing:.3px; }}
  .header span {{ display:inline-block; font-size:13px; color:rgba(255,255,255,.85); margin-top:4px; }}
  .body   {{ padding:32px; }}
  .body p  {{ margin:0 0 16px; font-size:14px; line-height:1.6; color:#252525; }}
  .btn    {{ display:inline-block; background:#28B4ED; color:#FFFFFF !important;
             text-decoration:none; padding:12px 28px; border-radius:6px;
             font-size:14px; font-weight:600; margin:8px 0 20px; }}
  .divider {{ border:none; border-top:1px solid #E8ECF0; margin:24px 0; }}
  .meta   {{ font-size:12px; color:#7A8A99; line-height:1.5; }}
  .footer {{ background:#F4F7FA; padding:20px 32px; text-align:center;
             font-size:11px; color:#7A8A99; border-top:1px solid #E8ECF0; }}
</style>
</head>
<body>
<div class="outer">
  <div class="card">
    <div class="header">
      <h1>HubWallet</h1>
      <span>Payments made simple</span>
    </div>
    <div class="body">
{body_content}
    </div>
    <div class="footer">
      &copy; HubWallet &bull; All rights reserved<br/>
      This email was sent automatically. Please do not reply.
    </div>
  </div>
</div>
</body>
</html>"""


def _auth_html(title: str, body_content: str) -> str:
    return _AUTH_HTML_WRAPPER.format(title=title, body_content=body_content)


# ---------------------------------------------------------------------------
# Payment / user_invite HTML wrapper
# (uses {{ primary_color }}, {{ accent_color }}, {{ logo_url }} variables)
# ---------------------------------------------------------------------------

_MERCHANT_HTML_WRAPPER = """\
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{title}</title>
<style>
  body {{ margin:0; padding:0; background:#F4F7FA; font-family:'Inter',Arial,sans-serif; color:#252525; }}
  .outer {{ width:100%; background:#F4F7FA; padding:40px 0; }}
  .card  {{ max-width:560px; margin:0 auto; background:#FFFFFF;
            border-radius:8px; overflow:hidden;
            box-shadow:0 2px 8px rgba(0,0,0,.08); }}
  .header {{ background:{{{{ primary_color }}}}; padding:28px 32px; text-align:center; }}
  .header img {{ max-height:48px; max-width:200px; object-fit:contain; margin-bottom:10px; display:block; margin:0 auto 10px; }}
  .header h1 {{ margin:0; color:#FFFFFF; font-size:20px; font-weight:700; }}
  .body   {{ padding:32px; }}
  .body p  {{ margin:0 0 16px; font-size:14px; line-height:1.6; color:#252525; }}
  .btn    {{ display:inline-block; background:{{{{ primary_color }}}}; color:#FFFFFF !important;
             text-decoration:none; padding:12px 28px; border-radius:6px;
             font-size:14px; font-weight:600; margin:8px 0 20px; }}
  .amount-box {{ background:#F4F7FA; border-left:4px solid {{{{ accent_color }}}};
                 padding:16px 20px; border-radius:4px; margin:16px 0; }}
  .amount-box .label {{ font-size:12px; color:#7A8A99; text-transform:uppercase;
                        letter-spacing:.6px; margin-bottom:4px; }}
  .amount-box .value {{ font-size:24px; font-weight:700; color:#252525; }}
  .detail-table {{ width:100%; border-collapse:collapse; font-size:13px; margin:16px 0; }}
  .detail-table td {{ padding:8px 0; border-bottom:1px solid #E8ECF0; color:#4A6271; }}
  .detail-table td:last-child {{ text-align:right; color:#252525; font-weight:500; }}
  .divider {{ border:none; border-top:1px solid #E8ECF0; margin:24px 0; }}
  .meta   {{ font-size:12px; color:#7A8A99; line-height:1.5; }}
  .footer {{ background:#F4F7FA; padding:20px 32px; text-align:center;
             font-size:11px; color:#7A8A99; border-top:1px solid #E8ECF0; }}
</style>
</head>
<body>
<div class="outer">
  <div class="card">
    <div class="header">
      {{% if logo_url %}}<img src="{{{{ logo_url }}}}" alt="{{{{ merchant_name }}}}" />{{% endif %}}
      <h1>{{{{ merchant_name }}}}</h1>
    </div>
    <div class="body">
{body_content}
    </div>
    <div class="footer">
      &copy; {{{{ merchant_name }}}} &bull; Powered by HubWallet<br/>
      This email was sent automatically. Please do not reply.
    </div>
  </div>
</div>
</body>
</html>"""


def _merchant_html(title: str, body_content: str) -> str:
    return _MERCHANT_HTML_WRAPPER.format(title=title, body_content=body_content)


# ---------------------------------------------------------------------------
# PDF (WeasyPrint-compatible, inline CSS, no external URLs)
# ---------------------------------------------------------------------------

_PDF_WRAPPER = """\
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>{title}</title>
<style>
  @page {{ size:A4; margin:20mm 18mm; }}
  * {{ box-sizing:border-box; }}
  body {{ font-family:Arial,Helvetica,sans-serif; font-size:12px;
          color:#252525; margin:0; padding:0; }}
  .page-header {{ border-bottom:3px solid {{{{ primary_color }}}}; padding-bottom:12px; margin-bottom:20px; }}
  .page-header .merchant-name {{ font-size:20px; font-weight:bold; color:{{{{ primary_color }}}}; }}
  .page-header .doc-title {{ font-size:14px; color:#4A6271; margin-top:2px; }}
  .meta-grid {{ display:grid; grid-template-columns:1fr 1fr; gap:8px; margin-bottom:20px; }}
  .meta-grid .item label {{ font-size:10px; color:#7A8A99; text-transform:uppercase; letter-spacing:.5px; }}
  .meta-grid .item .value {{ font-size:12px; font-weight:600; color:#252525; margin-top:2px; }}
  table {{ width:100%; border-collapse:collapse; margin-bottom:20px; }}
  table th {{ background:{{{{ primary_color }}}}; color:#FFFFFF; padding:8px 10px;
               text-align:left; font-size:11px; text-transform:uppercase; }}
  table td {{ padding:8px 10px; border-bottom:1px solid #E8ECF0; font-size:12px; }}
  table tr:nth-child(even) td {{ background:#F9FAFB; }}
  .totals-section {{ margin-left:auto; width:260px; }}
  .totals-row {{ display:flex; justify-content:space-between; padding:5px 0;
                 border-bottom:1px solid #E8ECF0; font-size:12px; }}
  .totals-row.grand {{ font-weight:bold; font-size:14px; border-top:2px solid {{{{ accent_color }}}};
                        border-bottom:none; padding-top:8px; }}
  .footer-note {{ font-size:10px; color:#7A8A99; margin-top:20px; border-top:1px solid #E8ECF0;
                  padding-top:10px; text-align:center; }}
</style>
</head>
<body>
{body_content}
</body>
</html>"""


def _pdf_html(title: str, body_content: str) -> str:
    return _PDF_WRAPPER.format(title=title, body_content=body_content)


# ---------------------------------------------------------------------------
# Template definitions
# ---------------------------------------------------------------------------

def _build_templates() -> List[dict]:
    templates: List[dict] = []

    # =========================================================================
    # AUTH TEMPLATES (8) — template_type = "auth", platform HubWallet branding
    # =========================================================================

    # 1. merchant_welcome
    templates.append(_row(
        template_key="merchant_welcome",
        template_name="Merchant Welcome",
        description="Sent to a new merchant after their account is created on the platform.",
        channel="email",
        template_type="auth",
        subject="Welcome to HubWallet, {{ merchant_name }}!",
        body_html=_auth_html(
            "Welcome to HubWallet",
            """\
      <p>Hi <strong>{{ merchant_name }}</strong>,</p>
      <p>Welcome to <strong>HubWallet</strong> — your all-in-one payments portal for growing businesses.
         Your account has been created and is ready to use.</p>
      <p>
        <a href="{{ login_url }}" class="btn">Log In to Your Portal</a>
      </p>
      <hr class="divider" />
      <p class="meta">
        Need help getting started? Our support team is here for you at
        <a href="mailto:{{ support_email }}">{{ support_email }}</a>.
      </p>""",
        ),
        body_text=(
            "Hi {{ merchant_name }},\n\n"
            "Welcome to HubWallet — your all-in-one payments portal.\n\n"
            "Log in here: {{ login_url }}\n\n"
            "Questions? Contact us at {{ support_email }}.\n\n"
            "— The HubWallet Team"
        ),
        variables=["merchant_name", "login_url", "support_email"],
    ))

    # 2. account_verification
    templates.append(_row(
        template_key="account_verification",
        template_name="Account Verification",
        description="Sent when a merchant needs to verify their email address.",
        channel="email",
        template_type="auth",
        subject="Verify your HubWallet account",
        body_html=_auth_html(
            "Verify Your Account",
            """\
      <p>Hi <strong>{{ merchant_name }}</strong>,</p>
      <p>Thanks for signing up. Please verify your email address by clicking the button below.
         This link will expire in <strong>{{ expires_in }}</strong>.</p>
      <p>
        <a href="{{ verification_url }}" class="btn">Verify Email Address</a>
      </p>
      <hr class="divider" />
      <p class="meta">
        If you didn't create a HubWallet account, you can safely ignore this email.
        This link expires in {{ expires_in }}.
      </p>""",
        ),
        body_text=(
            "Hi {{ merchant_name }},\n\n"
            "Please verify your email address by visiting:\n{{ verification_url }}\n\n"
            "This link expires in {{ expires_in }}.\n\n"
            "If you didn't sign up for HubWallet, please ignore this message.\n\n"
            "— The HubWallet Team"
        ),
        variables=["merchant_name", "verification_url", "expires_in"],
    ))

    # 3. sms_2fa_verification
    templates.append(_row(
        template_key="sms_2fa_verification",
        template_name="SMS Two-Factor Verification Code",
        description="SMS sent to a user during two-factor authentication.",
        channel="sms",
        template_type="auth",
        subject=None,
        body_html=None,
        body_text=(
            "HubWallet: Your verification code is {{ code }}. "
            "It expires in {{ expires_in }}. Do not share this code."
        ),
        variables=["code", "expires_in"],
    ))

    # 4. account_setup_complete
    templates.append(_row(
        template_key="account_setup_complete",
        template_name="Account Setup Complete",
        description="Sent after a merchant completes their initial account setup.",
        channel="email",
        template_type="auth",
        subject="Your HubWallet account is ready",
        body_html=_auth_html(
            "Account Ready",
            """\
      <p>Hi <strong>{{ merchant_name }}</strong>,</p>
      <p>Your HubWallet account setup is complete. You can now start accepting payments,
         managing customers, and running your business from one powerful dashboard.</p>
      <p>
        <a href="{{ dashboard_url }}" class="btn">Go to Dashboard</a>
      </p>
      <hr class="divider" />
      <p class="meta">
        If you have any questions or need assistance, our support team is always ready to help.
      </p>""",
        ),
        body_text=(
            "Hi {{ merchant_name }},\n\n"
            "Your HubWallet account setup is complete!\n\n"
            "Visit your dashboard: {{ dashboard_url }}\n\n"
            "— The HubWallet Team"
        ),
        variables=["merchant_name", "dashboard_url"],
    ))

    # 5. password_reset
    templates.append(_row(
        template_key="password_reset",
        template_name="Password Reset",
        description="Sent when a user requests a password reset link.",
        channel="email",
        template_type="auth",
        subject="Reset your HubWallet password",
        body_html=_auth_html(
            "Reset Your Password",
            """\
      <p>Hi <strong>{{ merchant_name }}</strong>,</p>
      <p>We received a request to reset the password for your HubWallet account.
         Click the button below to choose a new password. This link will expire in
         <strong>{{ expires_in }}</strong>.</p>
      <p>
        <a href="{{ reset_url }}" class="btn">Reset Password</a>
      </p>
      <hr class="divider" />
      <p class="meta">
        If you didn't request a password reset, please ignore this email — your password
        will not be changed. If you think your account may be compromised, please contact support.
      </p>""",
        ),
        body_text=(
            "Hi {{ merchant_name }},\n\n"
            "We received a request to reset your HubWallet password.\n\n"
            "Click here to reset it: {{ reset_url }}\n\n"
            "This link expires in {{ expires_in }}.\n\n"
            "If you didn't request this, please ignore this email.\n\n"
            "— The HubWallet Team"
        ),
        variables=["merchant_name", "reset_url", "expires_in"],
    ))

    # 6. password_changed
    templates.append(_row(
        template_key="password_changed",
        template_name="Password Changed",
        description="Sent as a security notification after a successful password change.",
        channel="email",
        template_type="auth",
        subject="Your password was changed",
        body_html=_auth_html(
            "Password Changed",
            """\
      <p>Hi <strong>{{ merchant_name }}</strong>,</p>
      <p>This is a confirmation that the password for your HubWallet account was successfully
         changed on <strong>{{ timestamp }}</strong>.</p>
      <p>If you made this change, no further action is needed.</p>
      <hr class="divider" />
      <p class="meta">
        If you did <strong>not</strong> make this change, please contact our support team
        immediately at <a href="mailto:{{ support_email }}">{{ support_email }}</a> to secure
        your account.
      </p>""",
        ),
        body_text=(
            "Hi {{ merchant_name }},\n\n"
            "Your HubWallet password was changed on {{ timestamp }}.\n\n"
            "If you did not make this change, contact us immediately at {{ support_email }}.\n\n"
            "— The HubWallet Team"
        ),
        variables=["merchant_name", "support_email", "timestamp"],
    ))

    # 7. email_change_confirmation
    templates.append(_row(
        template_key="email_change_confirmation",
        template_name="Email Change Confirmation",
        description="Sent to the new email address to confirm an email change request.",
        channel="email",
        template_type="auth",
        subject="Confirm your new email address",
        body_html=_auth_html(
            "Confirm New Email",
            """\
      <p>Hi <strong>{{ merchant_name }}</strong>,</p>
      <p>We received a request to update the email address on your HubWallet account
         to <strong>{{ new_email }}</strong>.</p>
      <p>Please confirm this change by clicking the button below:</p>
      <p>
        <a href="{{ confirmation_url }}" class="btn">Confirm New Email</a>
      </p>
      <hr class="divider" />
      <p class="meta">
        If you did not request this change, please ignore this email. Your original
        email address will remain active.
      </p>""",
        ),
        body_text=(
            "Hi {{ merchant_name }},\n\n"
            "Please confirm your new email address ({{ new_email }}) by visiting:\n"
            "{{ confirmation_url }}\n\n"
            "If you did not request this change, please ignore this email.\n\n"
            "— The HubWallet Team"
        ),
        variables=["merchant_name", "confirmation_url", "new_email"],
    ))

    # 8. new_login_alert
    templates.append(_row(
        template_key="new_login_alert",
        template_name="New Login Alert",
        description="Security alert sent when a sign-in is detected from a new device or location.",
        channel="email",
        template_type="auth",
        subject="New sign-in to your HubWallet account",
        body_html=_auth_html(
            "New Sign-In Detected",
            """\
      <p>Hi <strong>{{ merchant_name }}</strong>,</p>
      <p>We detected a new sign-in to your HubWallet account:</p>
      <table style="width:100%;border-collapse:collapse;font-size:13px;margin:12px 0;">
        <tr>
          <td style="padding:8px 0;border-bottom:1px solid #E8ECF0;color:#7A8A99;">Time</td>
          <td style="padding:8px 0;border-bottom:1px solid #E8ECF0;text-align:right;font-weight:500;">{{ timestamp }}</td>
        </tr>
        <tr>
          <td style="padding:8px 0;border-bottom:1px solid #E8ECF0;color:#7A8A99;">IP Address</td>
          <td style="padding:8px 0;border-bottom:1px solid #E8ECF0;text-align:right;font-weight:500;">{{ ip_address }}</td>
        </tr>
        <tr>
          <td style="padding:8px 0;color:#7A8A99;">Location</td>
          <td style="padding:8px 0;text-align:right;font-weight:500;">{{ location }}</td>
        </tr>
      </table>
      <p>If this was you, no action is needed.</p>
      <hr class="divider" />
      <p class="meta">
        If you don't recognize this sign-in, please
        <a href="mailto:{{ support_email }}">contact support</a> immediately and change
        your password.
      </p>""",
        ),
        body_text=(
            "Hi {{ merchant_name }},\n\n"
            "A new sign-in was detected on your HubWallet account.\n\n"
            "Time: {{ timestamp }}\n"
            "IP: {{ ip_address }}\n"
            "Location: {{ location }}\n\n"
            "If this wasn't you, contact {{ support_email }} immediately.\n\n"
            "— The HubWallet Team"
        ),
        variables=["merchant_name", "ip_address", "location", "timestamp", "support_email"],
    ))

    # =========================================================================
    # PAYMENT TEMPLATES (18) — template_type = "payment", merchant branding
    # =========================================================================

    # 9. invoice_email
    templates.append(_row(
        template_key="invoice_email",
        template_name="Invoice (Email)",
        description="Email sent to a customer with a link to view and pay their invoice.",
        channel="email",
        template_type="payment",
        subject="Invoice {{ invoice_number }} from {{ merchant_name }}",
        body_html=_merchant_html(
            "Invoice",
            """\
      <p>Hi <strong>{{ customer_name }}</strong>,</p>
      <p>Please find your invoice from <strong>{{ merchant_name }}</strong> below.
         You can pay securely online using the button below.</p>
      <div class="amount-box">
        <div class="label">Amount Due</div>
        <div class="value">{{ amount }}</div>
      </div>
      <table class="detail-table">
        <tr><td>Invoice Number</td><td>{{ invoice_number }}</td></tr>
        <tr><td>Due Date</td><td>{{ due_date }}</td></tr>
      </table>
      <p>
        <a href="{{ pay_url }}" class="btn">Pay Now</a>
      </p>
      <hr class="divider" />
      <p class="meta">
        If you have questions about this invoice, please contact {{ merchant_name }} directly.
      </p>""",
        ),
        body_text=(
            "Hi {{ customer_name }},\n\n"
            "You have a new invoice from {{ merchant_name }}.\n\n"
            "Invoice #: {{ invoice_number }}\n"
            "Amount Due: {{ amount }}\n"
            "Due Date: {{ due_date }}\n\n"
            "Pay here: {{ pay_url }}\n\n"
            "— {{ merchant_name }}"
        ),
        variables=[
            "merchant_name", "logo_url", "primary_color", "accent_color",
            "customer_name", "invoice_number", "amount", "due_date", "pay_url",
        ],
    ))

    # 10. invoice_send_sms
    templates.append(_row(
        template_key="invoice_send_sms",
        template_name="Invoice (SMS)",
        description="SMS sent to a customer with a brief summary and link to view and pay their invoice.",
        channel="sms",
        template_type="payment",
        subject=None,
        body_html=None,
        body_text=(
            "{{ merchant_name }}: Invoice {{ invoice_number }} — "
            "${{ amount }} due {{ due_date }}. "
            "Pay here: {{ pay_url }}"
            "{% if custom_message %}\n\n{{ custom_message }}{% endif %}\n\n"
            "Reply STOP to unsubscribe."
        ),
        variables=[
            "merchant_name", "customer_name", "invoice_number",
            "amount", "due_date", "pay_url", "custom_message",
        ],
    ))

    # 11. invoice_pdf
    templates.append(_row(
        template_key="invoice_pdf",
        template_name="Invoice (PDF)",
        description="WeasyPrint-rendered PDF version of a customer invoice.",
        channel="pdf",
        template_type="payment",
        subject=None,
        body_html=_pdf_html(
            "Invoice",
            """\
<div class="page-header">
  <div class="merchant-name">{{ merchant_name }}</div>
  <div class="doc-title">INVOICE</div>
</div>

<div class="meta-grid">
  <div class="item">
    <label>Invoice Number</label>
    <div class="value">{{ invoice_number }}</div>
  </div>
  <div class="item">
    <label>Issue Date</label>
    <div class="value">{{ issue_date }}</div>
  </div>
  <div class="item">
    <label>Due Date</label>
    <div class="value">{{ due_date }}</div>
  </div>
  <div class="item">
    <label>Status</label>
    <div class="value">{{ status }}</div>
  </div>
</div>

<div style="margin-bottom:16px;">
  <div style="font-size:10px;color:#7A8A99;text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px;">Bill To</div>
  <div style="font-weight:600;">{{ customer_name }}</div>
  <div style="color:#4A6271;">{{ customer_email }}</div>
  {% if customer_address %}<div style="color:#4A6271;">{{ customer_address }}</div>{% endif %}
</div>

<table>
  <thead>
    <tr>
      <th>Description</th>
      <th style="width:80px;text-align:right;">Qty</th>
      <th style="width:100px;text-align:right;">Unit Price</th>
      <th style="width:100px;text-align:right;">Total</th>
    </tr>
  </thead>
  <tbody>
    {% for item in line_items %}
    <tr>
      <td>{{ item.description }}</td>
      <td style="text-align:right;">{{ item.quantity }}</td>
      <td style="text-align:right;">{{ item.unit_price }}</td>
      <td style="text-align:right;">{{ item.total }}</td>
    </tr>
    {% endfor %}
  </tbody>
</table>

<div class="totals-section">
  {% if subtotal %}<div class="totals-row"><span>Subtotal</span><span>{{ subtotal }}</span></div>{% endif %}
  {% if discount %}<div class="totals-row"><span>Discount</span><span>-{{ discount }}</span></div>{% endif %}
  {% if tax %}<div class="totals-row"><span>Tax</span><span>{{ tax }}</span></div>{% endif %}
  <div class="totals-row grand"><span>Total Due</span><span>{{ amount }}</span></div>
</div>

{% if notes %}
<div style="margin-top:20px;font-size:11px;color:#4A6271;border-top:1px solid #E8ECF0;padding-top:12px;">
  <strong>Notes:</strong> {{ notes }}
</div>
{% endif %}

<div class="footer-note">
  Thank you for your business &bull; {{ merchant_name }} &bull; Powered by HubWallet
</div>""",
        ),
        body_text=None,
        variables=[
            "merchant_name", "primary_color", "accent_color",
            "customer_name", "customer_email", "customer_address",
            "invoice_number", "issue_date", "due_date", "status",
            "line_items", "subtotal", "discount", "tax", "amount", "notes",
        ],
    ))

    # 11. transaction_receipt_email
    templates.append(_row(
        template_key="transaction_receipt_email",
        template_name="Transaction Receipt (Email)",
        description="Email receipt sent to a customer after a successful payment.",
        channel="email",
        template_type="payment",
        subject="Payment receipt from {{ merchant_name }}",
        body_html=_merchant_html(
            "Payment Receipt",
            """\
      <p>Hi <strong>{{ customer_name }}</strong>,</p>
      <p>Thank you — your payment to <strong>{{ merchant_name }}</strong> was received
         successfully.</p>
      <div class="amount-box">
        <div class="label">Amount Paid</div>
        <div class="value">{{ amount }}</div>
      </div>
      <table class="detail-table">
        <tr><td>Transaction ID</td><td>{{ transaction_id }}</td></tr>
        <tr><td>Date</td><td>{{ date }}</td></tr>
        <tr><td>Card</td><td>ending in {{ last4 }}</td></tr>
      </table>
      <hr class="divider" />
      <p class="meta">
        Please keep this email as your receipt. If you have questions, contact
        {{ merchant_name }} directly.
      </p>""",
        ),
        body_text=(
            "Hi {{ customer_name }},\n\n"
            "Your payment to {{ merchant_name }} was received.\n\n"
            "Amount: {{ amount }}\n"
            "Transaction ID: {{ transaction_id }}\n"
            "Date: {{ date }}\n"
            "Card ending in: {{ last4 }}\n\n"
            "— {{ merchant_name }}"
        ),
        variables=[
            "merchant_name", "logo_url", "primary_color", "accent_color",
            "customer_name", "amount", "transaction_id", "date", "last4",
        ],
    ))

    # 12. transaction_receipt_pdf
    templates.append(_row(
        template_key="transaction_receipt_pdf",
        template_name="Transaction Receipt (PDF)",
        description="WeasyPrint-rendered PDF receipt for a completed payment.",
        channel="pdf",
        template_type="payment",
        subject=None,
        body_html=_pdf_html(
            "Payment Receipt",
            """\
<div class="page-header">
  <div class="merchant-name">{{ merchant_name }}</div>
  <div class="doc-title">PAYMENT RECEIPT</div>
</div>

<div class="meta-grid">
  <div class="item">
    <label>Transaction ID</label>
    <div class="value">{{ transaction_id }}</div>
  </div>
  <div class="item">
    <label>Date</label>
    <div class="value">{{ date }}</div>
  </div>
  <div class="item">
    <label>Status</label>
    <div class="value" style="color:green;">Paid</div>
  </div>
  <div class="item">
    <label>Payment Method</label>
    <div class="value">{{ payment_method }} ending {{ last4 }}</div>
  </div>
</div>

<div style="margin-bottom:16px;">
  <div style="font-size:10px;color:#7A8A99;text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px;">Paid By</div>
  <div style="font-weight:600;">{{ customer_name }}</div>
  <div style="color:#4A6271;">{{ customer_email }}</div>
</div>

<table>
  <thead>
    <tr>
      <th>Description</th>
      <th style="width:120px;text-align:right;">Amount</th>
    </tr>
  </thead>
  <tbody>
    {% for item in line_items %}
    <tr>
      <td>{{ item.description }}</td>
      <td style="text-align:right;">{{ item.amount }}</td>
    </tr>
    {% endfor %}
  </tbody>
</table>

<div class="totals-section">
  {% if tax %}<div class="totals-row"><span>Tax</span><span>{{ tax }}</span></div>{% endif %}
  <div class="totals-row grand"><span>Total Paid</span><span>{{ amount }}</span></div>
</div>

<div class="footer-note">
  {{ merchant_name }} &bull; Powered by HubWallet
</div>""",
        ),
        body_text=None,
        variables=[
            "merchant_name", "primary_color", "accent_color",
            "customer_name", "customer_email",
            "transaction_id", "date", "payment_method", "last4",
            "line_items", "tax", "amount",
        ],
    ))

    # 13. hpp_payment_request
    templates.append(_row(
        template_key="hpp_payment_request",
        template_name="HPP Payment Request (Email)",
        description="Email sent to a customer with a secure hosted payment page link.",
        channel="email",
        template_type="payment",
        subject="Payment request from {{ merchant_name }}",
        body_html=_merchant_html(
            "Payment Request",
            """\
      <p>Hi <strong>{{ customer_name }}</strong>,</p>
      <p><strong>{{ merchant_name }}</strong> has sent you a payment request.
         Please use the secure link below to complete your payment.</p>
      <div class="amount-box">
        <div class="label">Amount Due</div>
        <div class="value">{{ amount }}</div>
      </div>
      <table class="detail-table">
        <tr><td>Due Date</td><td>{{ due_date }}</td></tr>
      </table>
      <p>
        <a href="{{ hpp_link }}" class="btn">Pay Securely Now</a>
      </p>
      <hr class="divider" />
      <p class="meta">
        This payment link is unique to you. Do not share it. If you have questions,
        contact {{ merchant_name }} directly.
      </p>""",
        ),
        body_text=(
            "Hi {{ customer_name }},\n\n"
            "{{ merchant_name }} has sent you a payment request.\n\n"
            "Amount Due: {{ amount }}\n"
            "Due Date: {{ due_date }}\n\n"
            "Pay securely here: {{ hpp_link }}\n\n"
            "— {{ merchant_name }}"
        ),
        variables=[
            "merchant_name", "logo_url", "primary_color", "accent_color",
            "customer_name", "amount", "hpp_link", "due_date",
        ],
    ))

    # 14. hpp_payment_request_sms
    templates.append(_row(
        template_key="hpp_payment_request_sms",
        template_name="HPP Payment Request (SMS)",
        description="SMS sent to a customer with a short hosted payment page link.",
        channel="sms",
        template_type="payment",
        subject=None,
        body_html=None,
        body_text=(
            "{{ merchant_name }}: You have a payment of {{ amount }} due. "
            "Pay securely: {{ hpp_link }}"
        ),
        variables=["merchant_name", "amount", "hpp_link"],
    ))

    # 15. payment_success
    templates.append(_row(
        template_key="payment_success",
        template_name="Payment Confirmed",
        description="Email sent to a customer confirming their payment was processed.",
        channel="email",
        template_type="payment",
        subject="Payment confirmed — {{ merchant_name }}",
        body_html=_merchant_html(
            "Payment Confirmed",
            """\
      <p>Hi <strong>{{ customer_name }}</strong>,</p>
      <p>Great news — your payment to <strong>{{ merchant_name }}</strong> has been
         confirmed successfully!</p>
      <div class="amount-box">
        <div class="label">Amount Paid</div>
        <div class="value">{{ amount }}</div>
      </div>
      <table class="detail-table">
        <tr><td>Transaction ID</td><td>{{ transaction_id }}</td></tr>
        <tr><td>Date</td><td>{{ date }}</td></tr>
      </table>
      <hr class="divider" />
      <p class="meta">
        Please save this email for your records.
      </p>""",
        ),
        body_text=(
            "Hi {{ customer_name }},\n\n"
            "Your payment to {{ merchant_name }} has been confirmed.\n\n"
            "Amount: {{ amount }}\n"
            "Transaction ID: {{ transaction_id }}\n"
            "Date: {{ date }}\n\n"
            "— {{ merchant_name }}"
        ),
        variables=[
            "merchant_name", "customer_name", "amount", "transaction_id", "date",
        ],
    ))

    # 16. payment_failed
    templates.append(_row(
        template_key="payment_failed",
        template_name="Payment Failed",
        description="Email sent when a customer's payment attempt is declined or fails.",
        channel="email",
        template_type="payment",
        subject="Payment failed — action required",
        body_html=_merchant_html(
            "Payment Failed",
            """\
      <p>Hi <strong>{{ customer_name }}</strong>,</p>
      <p>Unfortunately your payment of <strong>{{ amount }}</strong> to
         <strong>{{ merchant_name }}</strong> could not be processed.</p>
      <table class="detail-table">
        <tr><td>Amount</td><td>{{ amount }}</td></tr>
        <tr><td>Reason</td><td>{{ reason }}</td></tr>
      </table>
      <p>Please update your payment details and try again:</p>
      <p>
        <a href="{{ retry_url }}" class="btn">Retry Payment</a>
      </p>
      <hr class="divider" />
      <p class="meta">
        If you continue to experience issues, please contact {{ merchant_name }} for assistance.
      </p>""",
        ),
        body_text=(
            "Hi {{ customer_name }},\n\n"
            "Your payment of {{ amount }} to {{ merchant_name }} failed.\n"
            "Reason: {{ reason }}\n\n"
            "Retry your payment here: {{ retry_url }}\n\n"
            "— {{ merchant_name }}"
        ),
        variables=[
            "merchant_name", "customer_name", "amount", "reason", "retry_url",
        ],
    ))

    # 17. payment_failed_retry_sms
    templates.append(_row(
        template_key="payment_failed_retry_sms",
        template_name="Payment Failed Retry (SMS)",
        description="SMS sent after a failed payment with a retry link.",
        channel="sms",
        template_type="payment",
        subject=None,
        body_html=None,
        body_text=(
            "{{ merchant_name }}: Your payment of {{ amount }} failed. "
            "Retry here: {{ retry_url }}"
        ),
        variables=["merchant_name", "amount", "retry_url"],
    ))

    # 18. authorization_request
    templates.append(_row(
        template_key="authorization_request",
        template_name="Authorization Request (Email)",
        description="Email sent to a customer requesting electronic authorization for a payment.",
        channel="email",
        template_type="payment",
        subject="Authorization required — {{ merchant_name }}",
        body_html=_merchant_html(
            "Authorization Required",
            """\
      <p>Hi <strong>{{ customer_name }}</strong>,</p>
      <p><strong>{{ merchant_name }}</strong> requires your authorization to process a payment.</p>
      <div class="amount-box">
        <div class="label">Authorization Amount</div>
        <div class="value">{{ amount }}</div>
      </div>
      <p>Please review and authorize the payment by clicking below:</p>
      <p>
        <a href="{{ auth_url }}" class="btn">Review &amp; Authorize</a>
      </p>
      <hr class="divider" />
      <p class="meta">
        By clicking the link above you will be taken to a secure page where you can
        review the details before authorizing. If you did not expect this request,
        please contact {{ merchant_name }}.
      </p>""",
        ),
        body_text=(
            "Hi {{ customer_name }},\n\n"
            "{{ merchant_name }} requires your authorization for a payment of {{ amount }}.\n\n"
            "Review and authorize here: {{ auth_url }}\n\n"
            "— {{ merchant_name }}"
        ),
        variables=[
            "merchant_name", "logo_url", "primary_color", "accent_color",
            "customer_name", "amount", "auth_url",
        ],
    ))

    # 19. authorization_request_sms
    templates.append(_row(
        template_key="authorization_request_sms",
        template_name="Authorization Request (SMS)",
        description="SMS sent to a customer requesting authorization for a payment.",
        channel="sms",
        template_type="payment",
        subject=None,
        body_html=None,
        body_text=(
            "{{ merchant_name }} requires your authorization. "
            "Hi {{ customer_name }}, review and sign here: {{ auth_url }}"
        ),
        variables=["merchant_name", "customer_name", "auth_url"],
    ))

    # 20. authorization_certificate_pdf
    templates.append(_row(
        template_key="authorization_certificate_pdf",
        template_name="Authorization Certificate (PDF)",
        description="WeasyPrint-rendered PDF certificate documenting a completed payment authorization.",
        channel="pdf",
        template_type="payment",
        subject=None,
        body_html=_pdf_html(
            "Authorization Certificate",
            """\
<div class="page-header">
  <div class="merchant-name">{{ merchant_name }}</div>
  <div class="doc-title">PAYMENT AUTHORIZATION CERTIFICATE</div>
</div>

<div class="meta-grid">
  <div class="item">
    <label>Authorization Type</label>
    <div class="value">{{ auth_type }}</div>
  </div>
  <div class="item">
    <label>Signed At</label>
    <div class="value">{{ signed_at }}</div>
  </div>
  <div class="item">
    <label>IP Address</label>
    <div class="value">{{ ip_address }}</div>
  </div>
  <div class="item">
    <label>Customer</label>
    <div class="value">{{ customer_name }}</div>
  </div>
</div>

<p style="font-size:12px;color:#4A6271;margin:16px 0;">
  The customer identified below has authorized the payment described in this certificate.
  This document serves as the electronic record of that authorization.
</p>

{% if signature_url %}
<div style="margin:20px 0;border:1px solid #E8ECF0;border-radius:4px;padding:12px;">
  <div style="font-size:10px;color:#7A8A99;text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px;">Customer Signature</div>
  <img src="{{ signature_url }}" style="max-width:260px;max-height:80px;" alt="Signature" />
</div>
{% endif %}

<div class="footer-note">
  This certificate was generated by HubWallet on behalf of {{ merchant_name }}.<br/>
  Document is legally binding as an electronic authorization under applicable law.
</div>""",
        ),
        body_text=None,
        variables=[
            "merchant_name", "logo_url", "primary_color", "accent_color",
            "customer_name", "auth_type", "signed_at", "ip_address", "signature_url",
        ],
    ))

    # 21. payment_method_update_request
    templates.append(_row(
        template_key="payment_method_update_request",
        template_name="Payment Method Update Request",
        description="Email sent to a customer asking them to update an expired or invalid payment method.",
        channel="email",
        template_type="payment",
        subject="Update your payment method — {{ merchant_name }}",
        body_html=_merchant_html(
            "Update Payment Method",
            """\
      <p>Hi <strong>{{ customer_name }}</strong>,</p>
      <p>The payment method on file for your account with <strong>{{ merchant_name }}</strong>
         needs to be updated. Please click below to add a new card or bank account.</p>
      <p>
        <a href="{{ update_url }}" class="btn">Update Payment Method</a>
      </p>
      <hr class="divider" />
      <p class="meta">
        Keeping your payment method up to date ensures uninterrupted service. If you need
        help, contact {{ merchant_name }} directly.
      </p>""",
        ),
        body_text=(
            "Hi {{ customer_name }},\n\n"
            "Your payment method with {{ merchant_name }} needs to be updated.\n\n"
            "Update it here: {{ update_url }}\n\n"
            "— {{ merchant_name }}"
        ),
        variables=[
            "merchant_name", "logo_url", "primary_color", "accent_color",
            "customer_name", "update_url",
        ],
    ))

    # 22. invoice_reminder
    templates.append(_row(
        template_key="invoice_reminder",
        template_name="Invoice Reminder",
        description="Reminder email sent before or on the due date of an unpaid invoice.",
        channel="email",
        template_type="payment",
        subject="Reminder: Invoice {{ invoice_number }} due {{ due_date }}",
        body_html=_merchant_html(
            "Invoice Reminder",
            """\
      <p>Hi <strong>{{ customer_name }}</strong>,</p>
      <p>This is a friendly reminder that invoice <strong>{{ invoice_number }}</strong>
         from <strong>{{ merchant_name }}</strong> is due on <strong>{{ due_date }}</strong>.</p>
      <div class="amount-box">
        <div class="label">Amount Due</div>
        <div class="value">{{ amount }}</div>
      </div>
      <p>
        <a href="{{ pay_url }}" class="btn">Pay Now</a>
      </p>
      <hr class="divider" />
      <p class="meta">
        If you have already made this payment, please disregard this reminder.
      </p>""",
        ),
        body_text=(
            "Hi {{ customer_name }},\n\n"
            "Reminder: Invoice {{ invoice_number }} from {{ merchant_name }} is due {{ due_date }}.\n\n"
            "Amount: {{ amount }}\n"
            "Pay here: {{ pay_url }}\n\n"
            "— {{ merchant_name }}"
        ),
        variables=[
            "merchant_name", "customer_name", "invoice_number",
            "amount", "due_date", "pay_url",
        ],
    ))

    # 23. subscription_created
    templates.append(_row(
        template_key="subscription_created",
        template_name="Subscription Created",
        description="Confirmation email sent when a customer's subscription is first activated.",
        channel="email",
        template_type="payment",
        subject="Subscription confirmed — {{ merchant_name }}",
        body_html=_merchant_html(
            "Subscription Confirmed",
            """\
      <p>Hi <strong>{{ customer_name }}</strong>,</p>
      <p>Your subscription to <strong>{{ plan_name }}</strong> with
         <strong>{{ merchant_name }}</strong> has been activated successfully.</p>
      <table class="detail-table">
        <tr><td>Plan</td><td>{{ plan_name }}</td></tr>
        <tr><td>Amount</td><td>{{ amount }}</td></tr>
        <tr><td>Next Billing Date</td><td>{{ next_billing_date }}</td></tr>
      </table>
      <hr class="divider" />
      <p class="meta">
        You will be charged automatically on your next billing date. To manage your
        subscription, contact {{ merchant_name }}.
      </p>""",
        ),
        body_text=(
            "Hi {{ customer_name }},\n\n"
            "Your subscription to {{ plan_name }} with {{ merchant_name }} is now active.\n\n"
            "Amount: {{ amount }}\n"
            "Next Billing Date: {{ next_billing_date }}\n\n"
            "— {{ merchant_name }}"
        ),
        variables=[
            "merchant_name", "customer_name", "plan_name",
            "amount", "next_billing_date",
        ],
    ))

    # 24. subscription_renewal
    templates.append(_row(
        template_key="subscription_renewal",
        template_name="Subscription Renewal",
        description="Email sent after a subscription successfully auto-renews.",
        channel="email",
        template_type="payment",
        subject="Subscription renewed — {{ merchant_name }}",
        body_html=_merchant_html(
            "Subscription Renewed",
            """\
      <p>Hi <strong>{{ customer_name }}</strong>,</p>
      <p>Your <strong>{{ plan_name }}</strong> subscription with <strong>{{ merchant_name }}</strong>
         has been renewed and payment processed successfully.</p>
      <table class="detail-table">
        <tr><td>Plan</td><td>{{ plan_name }}</td></tr>
        <tr><td>Amount Charged</td><td>{{ amount }}</td></tr>
        <tr><td>Transaction ID</td><td>{{ transaction_id }}</td></tr>
        <tr><td>Next Billing Date</td><td>{{ next_billing_date }}</td></tr>
      </table>
      <hr class="divider" />
      <p class="meta">
        Thank you for your continued business. Contact {{ merchant_name }} if you have questions.
      </p>""",
        ),
        body_text=(
            "Hi {{ customer_name }},\n\n"
            "Your {{ plan_name }} subscription with {{ merchant_name }} has been renewed.\n\n"
            "Amount: {{ amount }}\n"
            "Transaction ID: {{ transaction_id }}\n"
            "Next Billing Date: {{ next_billing_date }}\n\n"
            "— {{ merchant_name }}"
        ),
        variables=[
            "merchant_name", "customer_name", "plan_name",
            "amount", "next_billing_date", "transaction_id",
        ],
    ))

    # 25. subscription_cancelled
    templates.append(_row(
        template_key="subscription_cancelled",
        template_name="Subscription Cancelled",
        description="Email sent to confirm a subscription has been cancelled.",
        channel="email",
        template_type="payment",
        subject="Subscription cancelled — {{ merchant_name }}",
        body_html=_merchant_html(
            "Subscription Cancelled",
            """\
      <p>Hi <strong>{{ customer_name }}</strong>,</p>
      <p>Your <strong>{{ plan_name }}</strong> subscription with <strong>{{ merchant_name }}</strong>
         has been cancelled as of <strong>{{ cancelled_at }}</strong>.</p>
      <p>You will not be billed further. Any remaining access will continue until the end of
         the current billing period.</p>
      <hr class="divider" />
      <p class="meta">
        If you cancelled by mistake or wish to reactivate, please contact {{ merchant_name }}.
      </p>""",
        ),
        body_text=(
            "Hi {{ customer_name }},\n\n"
            "Your {{ plan_name }} subscription with {{ merchant_name }} has been cancelled "
            "as of {{ cancelled_at }}.\n\n"
            "You will not be billed further.\n\n"
            "— {{ merchant_name }}"
        ),
        variables=[
            "merchant_name", "customer_name", "plan_name", "cancelled_at",
        ],
    ))

    # 26. subscription_payment_failed
    templates.append(_row(
        template_key="subscription_payment_failed",
        template_name="Subscription Payment Failed",
        description="Email sent when an automatic subscription renewal charge fails.",
        channel="email",
        template_type="payment",
        subject="Subscription payment failed — {{ merchant_name }}",
        body_html=_merchant_html(
            "Subscription Payment Failed",
            """\
      <p>Hi <strong>{{ customer_name }}</strong>,</p>
      <p>We were unable to process your subscription payment of <strong>{{ amount }}</strong>
         for your <strong>{{ plan_name }}</strong> plan with <strong>{{ merchant_name }}</strong>.</p>
      <p>To avoid service interruption, please update your payment method and retry:</p>
      <p>
        <a href="{{ retry_url }}" class="btn">Update &amp; Retry</a>
      </p>
      <hr class="divider" />
      <p class="meta">
        If your subscription is not renewed soon it may be cancelled. Contact {{ merchant_name }}
        if you need assistance.
      </p>""",
        ),
        body_text=(
            "Hi {{ customer_name }},\n\n"
            "Your subscription payment of {{ amount }} for {{ plan_name }} with "
            "{{ merchant_name }} failed.\n\n"
            "Please update your payment method: {{ retry_url }}\n\n"
            "— {{ merchant_name }}"
        ),
        variables=[
            "merchant_name", "customer_name", "plan_name", "amount", "retry_url",
        ],
    ))

    # =========================================================================
    # USER INVITE TEMPLATES (2) — template_type = "user_invite"
    # =========================================================================

    # 27. user_invite
    templates.append(_row(
        template_key="user_invite",
        template_name="User Invite",
        description="Email sent to invite a new user to join a merchant's portal.",
        channel="email",
        template_type="user_invite",
        subject="You've been invited to {{ merchant_name }}'s portal",
        body_html=_merchant_html(
            "You're Invited",
            """\
      <p>Hi <strong>{{ invitee_name }}</strong>,</p>
      <p><strong>{{ inviter_name }}</strong> has invited you to join
         <strong>{{ merchant_name }}</strong>'s HubWallet payments portal.</p>
      <p>Click the button below to set up your account. This invitation expires in
         <strong>{{ expires_in }}</strong>.</p>
      <p>
        <a href="{{ invite_url }}" class="btn">Accept Invitation</a>
      </p>
      <hr class="divider" />
      <p class="meta">
        If you weren't expecting this invitation or don't recognize the sender,
        you can safely ignore this email.
      </p>""",
        ),
        body_text=(
            "Hi {{ invitee_name }},\n\n"
            "{{ inviter_name }} has invited you to join {{ merchant_name }}'s HubWallet portal.\n\n"
            "Accept your invitation: {{ invite_url }}\n\n"
            "This invitation expires in {{ expires_in }}.\n\n"
            "— {{ merchant_name }}"
        ),
        variables=[
            "merchant_name", "logo_url", "primary_color", "accent_color",
            "invitee_name", "inviter_name", "invite_url", "expires_in",
        ],
    ))

    # 28. user_invite_accepted
    templates.append(_row(
        template_key="user_invite_accepted",
        template_name="User Invite Accepted",
        description="Email sent to the inviter confirming that an invited user has accepted.",
        channel="email",
        template_type="user_invite",
        subject="{{ invitee_name }} accepted your invitation",
        body_html=_merchant_html(
            "Invitation Accepted",
            """\
      <p>Hi,</p>
      <p>Good news — <strong>{{ invitee_name }}</strong> has accepted your invitation to
         join <strong>{{ merchant_name }}</strong>'s HubWallet portal.</p>
      <table class="detail-table">
        <tr><td>Name</td><td>{{ invitee_name }}</td></tr>
        <tr><td>Email</td><td>{{ invitee_email }}</td></tr>
        <tr><td>Accepted At</td><td>{{ accepted_at }}</td></tr>
      </table>
      <hr class="divider" />
      <p class="meta">
        They now have access to your portal. You can manage team member permissions
        in your account settings.
      </p>""",
        ),
        body_text=(
            "Hi,\n\n"
            "{{ invitee_name }} ({{ invitee_email }}) has accepted your invitation to "
            "{{ merchant_name }}'s HubWallet portal.\n\n"
            "Accepted at: {{ accepted_at }}\n\n"
            "— HubWallet"
        ),
        variables=[
            "merchant_name", "invitee_name", "invitee_email", "accepted_at",
        ],
    ))

    return templates


# ---------------------------------------------------------------------------
# Seeder function
# ---------------------------------------------------------------------------

UPSERT_SQL = text(
    """
    INSERT INTO site_templates (
        template_key,
        template_name,
        description,
        channel,
        template_type,
        subject,
        body_html,
        body_text,
        primary_color,
        accent_color,
        text_color,
        variables,
        is_active,
        created_at
    ) VALUES (
        :template_key,
        :template_name,
        :description,
        :channel,
        :template_type,
        :subject,
        :body_html,
        :body_text,
        :primary_color,
        :accent_color,
        :text_color,
        CAST(:variables AS JSONB),
        :is_active,
        now()
    )
    ON CONFLICT (template_key) DO NOTHING
    """
)


def seed(db: Session) -> None:
    """
    Insert all 28 site templates into the database.

    Safe to run multiple times — uses ON CONFLICT DO NOTHING so existing
    rows are never overwritten.

    Args:
        db: An active SQLAlchemy Session.
    """
    templates = _build_templates()
    inserted = 0
    skipped = 0

    for t in templates:
        result = db.execute(UPSERT_SQL, t)
        if result.rowcount == 1:
            inserted += 1
        else:
            skipped += 1

    db.commit()
    logger.info(
        "site_templates seeder: %d inserted, %d already existed (skipped).",
        inserted,
        skipped,
    )
    print(f"site_templates seeder complete — {inserted} inserted, {skipped} skipped.")


# ---------------------------------------------------------------------------
# Standalone entry point
# ---------------------------------------------------------------------------

if __name__ == "__main__":
    import sys
    import os

    # Ensure the repo root is on sys.path so src.* imports resolve
    repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", ".."))
    if repo_root not in sys.path:
        sys.path.insert(0, repo_root)

    from src.core.database import SessionLocal  # noqa: E402 — deferred import

    logging.basicConfig(level=logging.INFO, format="%(levelname)s  %(message)s")

    db_session = SessionLocal()
    try:
        seed(db_session)
    except Exception as exc:
        db_session.rollback()
        logger.error("Seeder failed: %s", exc)
        sys.exit(1)
    finally:
        db_session.close()
