"""E-mail notifications for status-67 (Dopasowano) leads via SendGrid.

Sends SEPARATE mail per operator address — recipients never see each other.
Failures are logged and swallowed so the pipeline continues uninterrupted.
"""

from __future__ import annotations

import html as html_mod
import logging

from agent_samochodowy.config import Settings
from agent_samochodowy.models import MatchResult, PartQuery, Post

logger = logging.getLogger(__name__)

# Muted palette
_CLR_PRIMARY = "#2563eb"   # blue-600
_CLR_FB = "#1877F2"
_CLR_GREEN = "#16a34a"
_CLR_MUTED = "#6b7280"     # gray-500
_CLR_BG = "#f3f4f6"        # gray-100
_CLR_CARD = "#f9fafb"      # gray-50
_CLR_BORDER = "#e5e7eb"    # gray-200
_CLR_TEXT = "#111827"       # gray-900


class MatchNotifier:
    """SendGrid notifier for matched leads. Safe to use even without a key."""

    def __init__(self, settings: Settings) -> None:
        self._api_key = settings.sendgrid_api_key
        self._from_email = settings.notify_email_from
        self._to_emails = [
            e.strip() for e in settings.notify_email_to.split(",") if e.strip()
        ]
        self._max_per_cycle = settings.notify_max_per_cycle
        self._dgred_base = settings.dgred_base_url.rstrip("/")
        self._sent_count = 0
        self._notified_posts: set[str] = set()

    @property
    def enabled(self) -> bool:
        return bool(self._api_key and self._to_emails)

    def notify_match(
        self,
        post: Post,
        query: PartQuery,
        result: MatchResult,
        client_id: int | str,
        reply_text: str,
    ) -> bool:
        """Send notification for a Dopasowano lead. Returns True if all sent."""
        if not self.enabled:
            logger.debug("Notifier disabled (no API key or recipients)")
            return False

        if post.post_id in self._notified_posts:
            logger.debug("Already notified for post %s, skipping", post.post_id)
            return False

        if self._sent_count >= self._max_per_cycle:
            logger.warning(
                "Notification throttle reached (%d/%d), skipping post %s",
                self._sent_count, self._max_per_cycle, post.post_id,
            )
            return False

        top_offer = result.offers[0] if result.offers else None
        subject = self._build_subject(query)
        body_html = self._build_html(post, query, top_offer, client_id, reply_text)

        all_ok = True
        for recipient in self._to_emails:
            try:
                self._send_single(recipient, subject, body_html)
            except Exception:
                logger.exception(
                    "SendGrid error for post %s to %s — continuing",
                    post.post_id, recipient,
                )
                all_ok = False

        self._notified_posts.add(post.post_id)
        self._sent_count += 1
        logger.info(
            "Notification sent for post %s to %d recipient(s) (%d/%d)",
            post.post_id, len(self._to_emails), self._sent_count, self._max_per_cycle,
        )
        return all_ok

    # ------------------------------------------------------------------
    # Subject
    # ------------------------------------------------------------------

    def _build_subject(self, query: PartQuery) -> str:
        part = query.category or "część"
        vehicle_parts = [p for p in (query.brand, query.model) if p]
        vehicle = " ".join(vehicle_parts) if vehicle_parts else ""
        if vehicle:
            return f"Nowe dopasowanie: {part} {vehicle}"
        return f"Nowe dopasowanie: {part}"

    # ------------------------------------------------------------------
    # HTML builder — mobile-first, all inline CSS
    # ------------------------------------------------------------------

    def _build_html(
        self,
        post: Post,
        query: PartQuery,
        top_offer,
        client_id: int | str,
        reply_text: str,
    ) -> str:
        e = html_mod.escape
        dgred_link = f"{self._dgred_base.replace('/api/v1', '')}/client/{client_id}"

        part = e(query.category or "część")
        vehicle_parts = [p for p in (query.brand, query.model) if p]
        vehicle = e(" ".join(vehicle_parts)) if vehicle_parts else ""
        header_title = f"{part} {vehicle}".strip()

        vehicle_full = [p for p in (query.brand, query.model, query.year) if p]
        vehicle_str = e(" ".join(vehicle_full)) if vehicle_full else "—"
        oe_str = e(", ".join(query.oe_numbers)) if query.oe_numbers else "—"

        # Post link
        post_url = post.post_url or ""
        post_btn = (
            self._btn_block("Otwórz post na Facebooku", post_url, _CLR_FB)
            if post_url
            else f'<div style="color:#dc2626;font-size:14px;padding:8px 0">Brak linku do posta</div>'
        )

        # Profile link
        profile_btn = (
            self._btn_block("Profil autora", post.author_profile_url, _CLR_MUTED)
            if post.author_profile_url else ""
        )

        # Offer card
        offer_html = ""
        if top_offer:
            price_str = self._format_price(top_offer)
            offer_url = top_offer.url or ""
            see_btn = self._btn_block("Zobacz ofertę", offer_url, _CLR_GREEN) if offer_url else ""
            offer_html = f"""
<!--[if mso]><table width="100%"><tr><td><![endif]-->
<table width="100%" cellpadding="0" cellspacing="0" style="background:{_CLR_CARD};border:1px solid {_CLR_BORDER};border-radius:8px;margin:16px 0 8px">
<tr><td style="padding:20px">
  <div style="font-size:12px;text-transform:uppercase;letter-spacing:0.5px;color:{_CLR_MUTED};margin-bottom:10px">Dopasowana oferta</div>
  <div style="font-size:15px;line-height:1.45;color:{_CLR_TEXT};margin-bottom:12px;word-break:break-word">{e(top_offer.title)}</div>
  <div style="font-size:28px;font-weight:700;color:{_CLR_TEXT};margin-bottom:16px">{e(price_str)}</div>
  {see_btn}
</td></tr>
</table>
<!--[if mso]></td></tr></table><![endif]-->"""

        # Reply proposal
        reply_html = f"""
<table width="100%" cellpadding="0" cellspacing="0" style="margin:16px 0 8px">
<tr><td>
  <div style="font-size:12px;text-transform:uppercase;letter-spacing:0.5px;color:{_CLR_MUTED};margin-bottom:8px">Gotowa propozycja odpowiedzi</div>
  <div style="background:#eff6ff;border-left:3px solid {_CLR_PRIMARY};padding:14px 16px;font-size:15px;line-height:1.5;color:{_CLR_TEXT};border-radius:0 6px 6px 0;word-break:break-word">{e(reply_text)}</div>
</td></tr>
</table>"""

        return f"""<!DOCTYPE html>
<html lang="pl"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>{e(header_title)}</title></head>
<body style="margin:0;padding:0;background:{_CLR_BG};font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif;-webkit-text-size-adjust:100%">

<!-- Wrapper -->
<table width="100%" cellpadding="0" cellspacing="0" style="background:{_CLR_BG}">
<tr><td style="padding:20px 12px" align="center">

<!-- Card -->
<table width="100%" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:10px;max-width:560px;overflow:hidden">

  <!-- Header -->
  <tr><td style="padding:24px 24px 20px">
    <div style="font-size:12px;text-transform:uppercase;letter-spacing:0.5px;color:{_CLR_MUTED};margin-bottom:4px">Nowe dopasowanie</div>
    <div style="font-size:22px;font-weight:700;color:{_CLR_TEXT};line-height:1.3">{header_title}</div>
  </td></tr>

  <!-- Divider -->
  <tr><td style="padding:0 24px"><div style="border-top:1px solid {_CLR_BORDER}"></div></td></tr>

  <!-- Zapytanie -->
  <tr><td style="padding:20px 24px">
    <div style="font-size:12px;text-transform:uppercase;letter-spacing:0.5px;color:{_CLR_MUTED};margin-bottom:10px">Zapytanie z grupy {e(post.group)}</div>
    <div style="background:#fffbeb;border-left:3px solid #f59e0b;padding:14px 16px;font-size:15px;line-height:1.5;color:{_CLR_TEXT};border-radius:0 6px 6px 0;word-break:break-word">{e(post.text)}</div>
    <table width="100%" cellpadding="0" cellspacing="0" style="margin-top:14px">
      <tr><td style="font-size:15px;color:{_CLR_TEXT};padding-bottom:4px"><strong>{e(post.author_name)}</strong></td></tr>
      <tr><td style="font-size:13px;color:{_CLR_MUTED};padding-bottom:14px">Pojazd: {vehicle_str} &nbsp;&middot;&nbsp; OE: {oe_str}</td></tr>
      <tr><td>{post_btn}</td></tr>
      <tr><td style="padding-top:6px">{profile_btn}</td></tr>
    </table>
  </td></tr>

  <!-- Divider -->
  <tr><td style="padding:0 24px"><div style="border-top:1px solid {_CLR_BORDER}"></div></td></tr>

  <!-- Oferta + Propozycja -->
  <tr><td style="padding:8px 24px 20px">
    {offer_html}
    {reply_html}
  </td></tr>

  <!-- Divider -->
  <tr><td style="padding:0 24px"><div style="border-top:1px solid {_CLR_BORDER}"></div></td></tr>

  <!-- CTA -->
  <tr><td style="padding:20px 24px" align="center">
    {self._btn_block("Otwórz lead w dgred", dgred_link, _CLR_PRIMARY)}
  </td></tr>

  <!-- Footer -->
  <tr><td style="padding:16px 24px;border-top:1px solid {_CLR_BORDER}">
    <div style="font-size:12px;color:{_CLR_MUTED};text-align:center">Agent Samochodowy &middot; powiadomienie automatyczne</div>
  </td></tr>

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

</td></tr>
</table>
<!-- /Wrapper -->

</body></html>"""

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

    def _send_single(self, recipient: str, subject: str, html_content: str) -> None:
        """Send one mail to one recipient via SendGrid v3 API."""
        from sendgrid import SendGridAPIClient
        from sendgrid.helpers.mail import Email, Mail

        from_email = self._parse_email(self._from_email)
        message = Mail(
            from_email=from_email,
            to_emails=recipient,
            subject=subject,
            html_content=html_content,
        )
        sg = SendGridAPIClient(self._api_key)
        response = sg.send(message)
        if response.status_code >= 400:
            raise RuntimeError(
                f"SendGrid HTTP {response.status_code}: {response.body}"
            )

    @staticmethod
    def _parse_email(raw: str) -> "Email":
        """Parse 'Display Name <addr>' or plain 'addr' into SendGrid Email."""
        from sendgrid.helpers.mail import Email

        raw = raw.strip()
        if "<" in raw and raw.endswith(">"):
            name, addr = raw.rsplit("<", 1)
            return Email(addr.rstrip(">").strip(), name.strip())
        return Email(raw)

    @staticmethod
    def _btn_block(label: str, url: str, color: str) -> str:
        """Full-width block button — works on mobile without media queries."""
        return (
            f'<table width="100%" cellpadding="0" cellspacing="0"><tr><td align="center">'
            f'<a href="{url}" style="display:block;background:{color};color:#ffffff;'
            f'padding:14px 24px;text-decoration:none;border-radius:6px;font-size:15px;'
            f'font-weight:600;text-align:center;line-height:1.4;'
            f'mso-padding-alt:14px 24px">{html_mod.escape(label)}</a>'
            f'</td></tr></table>'
        )

    @staticmethod
    def _format_price(offer) -> str:
        if offer.price is not None:
            cur = offer.currency or "PLN"
            if offer.price == int(offer.price):
                return f"{int(offer.price)} {cur}"
            return f"{offer.price:.2f} {cur}"
        return "do uzgodnienia"
