"""
BIBIVIDI — Transactional email (TODO-18)
Sends the quarterly team savings digest to the account owner.

Supported providers (set via BIBIVIDI_MAILER_PROVIDER):
  resend    — Resend API (https://resend.com), default
  postmark  — Postmark transactional email

Both are pure-HTTP APIs — no extra dependencies beyond httpx (already installed).
If no API key is configured the digest is written to the log only.
"""
from __future__ import annotations

import logging
from dataclasses import dataclass

logger = logging.getLogger(__name__)

_CO2_G_PER_TOKEN: float = 0.003


# ── Email content builders ─────────────────────────────────────────────────────

@dataclass
class QuarterlyEmail:
    subject: str
    html: str
    text: str


def build_quarterly_email(summary: dict, quarter_label: str) -> QuarterlyEmail:
    """Build the quarterly digest email from a stats summary dict.

    ``summary`` must have the shape returned by ``StatsTracker.quarterly_summary()``.
    ``quarter_label`` is e.g. "2026-Q1".
    """
    tokens_saved = summary.get("tokens_saved", 0)
    savings_eur = summary.get("savings_eur", 0.0)
    bibividi_share_eur = summary.get("bibividi_share_eur", 0.0)
    net_eur = savings_eur - bibividi_share_eur
    co2_g = tokens_saved * _CO2_G_PER_TOKEN
    calls = summary.get("calls", 0)
    top_skills: list[dict] = summary.get("top_skills", [])

    co2_str = _fmt_co2(co2_g)
    tokens_str = _fmt_tokens(tokens_saved)

    subject = (
        f"BIBIVIDI saved your team €{savings_eur:.2f} in {quarter_label} "
        f"— {co2_str} CO₂eq avoided"
    )

    # ── Skills table rows ──────────────────────────────────────────────────────
    skills_html = ""
    skills_text = ""
    for i, skill in enumerate(top_skills[:3], 1):
        skills_html += (
            f"<tr>"
            f"<td style='padding:6px 12px;color:#6c757d'>{i}</td>"
            f"<td style='padding:6px 12px;font-weight:600'>{skill['skill_id']}</td>"
            f"<td style='padding:6px 12px;text-align:right'>{skill['uses']:,} uses</td>"
            f"</tr>\n"
        )
        skills_text += f"  {i}. {skill['skill_id']} — {skill['uses']:,} uses\n"

    if not skills_html:
        skills_html = (
            "<tr><td colspan='3' style='padding:12px;color:#6c757d'>"
            "No skills used this quarter</td></tr>"
        )
        skills_text = "  No skills recorded this quarter.\n"

    html = f"""<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <title>{subject}</title>
</head>
<body style="margin:0;padding:0;background:#f8f9fa;font-family:system-ui,-apple-system,sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0">
    <tr>
      <td align="center" style="padding:2rem 1rem;">
        <table width="600" cellpadding="0" cellspacing="0"
               style="background:white;border-radius:8px;overflow:hidden;
                      box-shadow:0 1px 3px rgba(0,0,0,0.1);">
          <!-- Header -->
          <tr>
            <td style="background:#1a1a2e;padding:2rem 2.5rem;">
              <p style="color:#adb5bd;margin:0;font-size:0.85rem;">
                Quarterly savings report · {quarter_label}
              </p>
              <h1 style="color:white;margin:0.5rem 0 0;font-size:1.5rem;">
                BIBIVIDI saved your team
                <span style="color:#52b788;">€{savings_eur:.2f}</span>
                this quarter
              </h1>
            </td>
          </tr>

          <!-- KPIs -->
          <tr>
            <td style="padding:2rem 2.5rem;">
              <table width="100%" cellpadding="0" cellspacing="0">
                <tr>
                  <td style="text-align:center;padding:1rem;
                             background:#f0fdf4;border-radius:6px;">
                    <p style="margin:0;font-size:1.75rem;font-weight:700;
                              color:#2d6a4f;">{tokens_str}</p>
                    <p style="margin:0.25rem 0 0;font-size:0.8rem;color:#6c757d;">
                      Tokens saved
                    </p>
                  </td>
                  <td width="16"></td>
                  <td style="text-align:center;padding:1rem;
                             background:#f0fdf4;border-radius:6px;">
                    <p style="margin:0;font-size:1.75rem;font-weight:700;
                              color:#2d6a4f;">{co2_str}</p>
                    <p style="margin:0.25rem 0 0;font-size:0.8rem;color:#6c757d;">
                      CO₂eq avoided
                    </p>
                  </td>
                  <td width="16"></td>
                  <td style="text-align:center;padding:1rem;
                             background:#f0fdf4;border-radius:6px;">
                    <p style="margin:0;font-size:1.75rem;font-weight:700;
                              color:#2d6a4f;">€{net_eur:.2f}</p>
                    <p style="margin:0.25rem 0 0;font-size:0.8rem;color:#6c757d;">
                      Net savings after BIBIVIDI fee
                    </p>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <!-- Billing row -->
          <tr>
            <td style="padding:0 2.5rem 1.5rem;">
              <p style="margin:0;font-size:0.875rem;color:#495057;">
                Gross savings: <strong>€{savings_eur:.4f}</strong>
                &nbsp;·&nbsp;
                BIBIVIDI fee ({quarter_label}): <strong>€{bibividi_share_eur:.4f}</strong>
                &nbsp;·&nbsp;
                Your net gain: <strong>€{net_eur:.4f}</strong>
                &nbsp;·&nbsp;
                Requests: <strong>{calls:,}</strong>
              </p>
            </td>
          </tr>

          <!-- Top skills -->
          <tr>
            <td style="padding:0 2.5rem 1.5rem;">
              <h2 style="font-size:0.875rem;text-transform:uppercase;
                         letter-spacing:0.05em;color:#6c757d;margin:0 0 0.75rem;">
                Top skills this quarter
              </h2>
              <table width="100%" cellpadding="0" cellspacing="0"
                     style="border:1px solid #dee2e6;border-radius:6px;
                            overflow:hidden;border-collapse:collapse;">
                <thead>
                  <tr style="background:#f8f9fa;">
                    <th style="padding:8px 12px;text-align:left;
                               font-size:0.8rem;color:#495057;">#</th>
                    <th style="padding:8px 12px;text-align:left;
                               font-size:0.8rem;color:#495057;">Skill</th>
                    <th style="padding:8px 12px;text-align:right;
                               font-size:0.8rem;color:#495057;">Uses</th>
                  </tr>
                </thead>
                <tbody>
                  {skills_html}
                </tbody>
              </table>
            </td>
          </tr>

          <!-- CTA -->
          <tr>
            <td style="padding:0 2.5rem 2rem;">
              <p style="margin:0;font-size:0.875rem;color:#6c757d;">
                Share these savings with your team →
                <a href="http://localhost:8080/bibividi/badge.svg"
                   style="color:#2d6a4f;">embed the savings badge</a>
              </p>
            </td>
          </tr>

          <!-- Footer -->
          <tr>
            <td style="background:#f8f9fa;padding:1.25rem 2.5rem;
                       border-top:1px solid #dee2e6;">
              <p style="margin:0;font-size:0.75rem;color:#adb5bd;">
                BIBIVIDI · AI token optimization · bibividi.ai<br>
                CO₂ estimate: {tokens_saved:,} tokens × 0.003 gCO₂eq/token.
                Independent GHG auditor verification recommended for CSRD Scope 3 filings.
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>"""

    text = (
        f"BIBIVIDI Quarterly Digest — {quarter_label}\n"
        f"{'=' * 48}\n\n"
        f"Tokens saved      : {tokens_str}\n"
        f"CO₂eq avoided     : {co2_str}\n"
        f"Gross savings     : €{savings_eur:.4f}\n"
        f"BIBIVIDI fee      : €{bibividi_share_eur:.4f}\n"
        f"Your net savings  : €{net_eur:.4f}\n"
        f"API requests      : {calls:,}\n\n"
        f"Top skills:\n{skills_text}\n"
        f"CO₂ note: {tokens_saved:,} tokens × 0.003 gCO₂eq/token.\n"
        f"Independent GHG auditor verification recommended for CSRD Scope 3 filings.\n"
    )

    return QuarterlyEmail(subject=subject, html=html, text=text)


async def send_quarterly_email(
    to: str,
    summary: dict,
    quarter_label: str,
) -> bool:
    """Send the quarterly digest email.

    Routes to Resend, Postmark, or log-only based on BIBIVIDI_MAILER_PROVIDER.
    Returns True on success, False on failure or if no mailer is configured.
    """
    from bvd.config import settings

    email = build_quarterly_email(summary, quarter_label)

    if not settings.mailer_api_key:
        logger.info(
            "Quarterly digest (log-only — no BIBIVIDI_MAILER_API_KEY):\n%s",
            email.text,
        )
        return False

    provider = settings.mailer_provider.lower()
    if provider == "postmark":
        return await _send_postmark(to, email, settings)
    return await _send_resend(to, email, settings)


# ── Provider implementations ──────────────────────────────────────────────────

async def _send_resend(to: str, email: QuarterlyEmail, settings: object) -> bool:
    """Send via Resend API (https://resend.com)."""
    import httpx

    from_addr = getattr(settings, "mailer_from", "BIBIVIDI <noreply@localhost>")
    api_key = getattr(settings, "mailer_api_key", None)

    try:
        async with httpx.AsyncClient(timeout=15.0) as client:
            resp = await client.post(
                "https://api.resend.com/emails",
                headers={
                    "Authorization": f"Bearer {api_key}",
                    "Content-Type": "application/json",
                },
                json={
                    "from": from_addr,
                    "to": [to],
                    "subject": email.subject,
                    "html": email.html,
                    "text": email.text,
                },
            )
        if resp.status_code in (200, 201):
            logger.info("Quarterly digest sent via Resend to %s", to)
            return True
        logger.error(
            "Resend API error %d: %s", resp.status_code, resp.text[:300]
        )
        return False
    except Exception as exc:
        logger.error("Resend send failed: %s", exc)
        return False


async def _send_postmark(to: str, email: QuarterlyEmail, settings: object) -> bool:
    """Send via Postmark API (https://postmarkapp.com)."""
    import httpx

    from_addr = getattr(settings, "mailer_from", "noreply@localhost")
    api_key = getattr(settings, "mailer_api_key", None)

    try:
        async with httpx.AsyncClient(timeout=15.0) as client:
            resp = await client.post(
                "https://api.postmarkapp.com/email",
                headers={  # type: ignore[arg-type]
                    "X-Postmark-Server-Token": api_key,
                    "Content-Type": "application/json",
                },
                json={
                    "From": from_addr,
                    "To": to,
                    "Subject": email.subject,
                    "HtmlBody": email.html,
                    "TextBody": email.text,
                    "MessageStream": "outbound",
                },
            )
        if resp.status_code == 200:
            logger.info("Quarterly digest sent via Postmark to %s", to)
            return True
        logger.error(
            "Postmark API error %d: %s", resp.status_code, resp.text[:300]
        )
        return False
    except Exception as exc:
        logger.error("Postmark send failed: %s", exc)
        return False


# ── Helpers ───────────────────────────────────────────────────────────────────

def _fmt_tokens(n: int) -> str:
    if n >= 1_000_000_000:
        return f"{n / 1_000_000_000:.2f}B"
    if n >= 1_000_000:
        return f"{n / 1_000_000:.2f}M"
    if n >= 1000:
        return f"{n / 1000:.1f}K"
    return str(n)


def _fmt_co2(g: float) -> str:
    if g >= 1_000_000:
        return f"{g / 1_000_000:.3f}t"
    if g >= 1000:
        return f"{g / 1000:.2f}kg"
    return f"{g:.1f}g"
