"""
email_sender.py — Transactional email via SMTP (smtplib, zero extra deps).

Configuration (in user_configs or environment variables):
    SMTP_HOST     — default: smtp.gmail.com
    SMTP_PORT     — default: 587
    SMTP_USER     — sender email address
    SMTP_PASSWORD — sender SMTP password / app password
    SMTP_FROM     — display name + address (default: SMTP_USER value)

Environment variables override user_configs so the server admin can set a
shared SMTP relay without exposing credentials to end users.
"""

from __future__ import annotations

import logging
import os
import smtplib
import ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

logger = logging.getLogger("email_sender")


def _get_smtp_config(user_configs: dict) -> dict:
    """Merge env vars (higher priority) over user_configs."""
    return {
        "host":     os.environ.get("SMTP_HOST")     or user_configs.get("smtp_host", "smtp.gmail.com"),
        "port":     int(os.environ.get("SMTP_PORT") or user_configs.get("smtp_port", 587)),
        "user":     os.environ.get("SMTP_USER")     or user_configs.get("smtp_user", ""),
        "password": os.environ.get("SMTP_PASSWORD") or user_configs.get("smtp_password", ""),
        "from":     os.environ.get("SMTP_FROM")     or user_configs.get("smtp_from", ""),
    }


def send_email(
    to: str,
    subject: str,
    body_html: str,
    body_text: str = "",
    user_configs: dict | None = None,
) -> bool:
    """
    Send a transactional email.

    Parameters
    ----------
    to          : recipient email address
    subject     : email subject
    body_html   : HTML body
    body_text   : plain-text fallback (auto-generated from subject if empty)
    user_configs: dict with SMTP settings (merged with env vars)

    Returns True on success, False on failure (logs error).
    """
    cfg = _get_smtp_config(user_configs or {})
    if not cfg["user"] or not cfg["password"]:
        logger.warning("Email not sent: SMTP_USER / SMTP_PASSWORD not configured.")
        return False
    if not to:
        logger.warning("Email not sent: no recipient address.")
        return False

    sender = cfg["from"] or cfg["user"]
    body_text = body_text or f"{subject}\n\nView in your dashboard for details."

    msg = MIMEMultipart("alternative")
    msg["Subject"] = subject
    msg["From"]    = sender
    msg["To"]      = to
    msg.attach(MIMEText(body_text, "plain"))
    msg.attach(MIMEText(body_html, "html"))

    try:
        ctx = ssl.create_default_context()
        with smtplib.SMTP(cfg["host"], cfg["port"]) as server:
            server.ehlo()
            server.starttls(context=ctx)
            server.login(cfg["user"], cfg["password"])
            server.sendmail(sender, [to], msg.as_string())
        logger.info(f"Email sent to {to}: {subject}")
        return True
    except Exception as e:
        logger.error(f"Failed to send email to {to}: {e}")
        return False


# ── Pre-built email templates ─────────────────────────────────────────────────

def alert_email(
    to: str,
    domain: str,
    risk_score: float,
    question: str,
    chain_id: int,
    dashboard_url: str = "https://app.llm-guard-kit.com",
    user_configs: dict | None = None,
) -> bool:
    """Send a guardrail alert notification email."""
    pct   = f"{risk_score:.0%}"
    color = "#ef4444" if risk_score >= 0.65 else "#f59e0b"
    q_safe = (question or "")[:200].replace("<", "&lt;").replace(">", "&gt;")
    subject = f"[llm-guard-kit] Risk alert: {domain} scored {pct}"
    body_html = f"""
<!DOCTYPE html>
<html>
<body style="font-family:sans-serif;background:#0f0f0f;color:#e5e7eb;padding:32px;">
  <div style="max-width:560px;margin:0 auto;background:#1f2937;border-radius:12px;padding:28px;border:1px solid #374151;">
    <h2 style="color:#f9fafb;margin:0 0 8px 0;">Risk Alert Triggered</h2>
    <p style="color:#9ca3af;font-size:14px;margin:0 0 24px 0;">Domain: <strong style="color:#e5e7eb">{domain}</strong></p>

    <div style="background:#111827;border-radius:8px;padding:16px;margin-bottom:20px;">
      <div style="font-size:32px;font-weight:bold;color:{color};">{pct}</div>
      <div style="font-size:12px;color:#6b7280;margin-top:4px;">Risk Score</div>
    </div>

    <div style="margin-bottom:20px;">
      <div style="font-size:12px;color:#9ca3af;margin-bottom:4px;">Question</div>
      <div style="background:#111827;border-radius:6px;padding:12px;font-size:13px;color:#d1d5db;">{q_safe}</div>
    </div>

    <div style="margin-bottom:24px;">
      <div style="font-size:12px;color:#9ca3af;">Chain ID: <code style="color:#a78bfa">#{chain_id}</code></div>
    </div>

    <a href="{dashboard_url}/app" style="display:inline-block;background:#4f46e5;color:#fff;
       text-decoration:none;padding:10px 20px;border-radius:8px;font-size:14px;font-weight:600;">
      View Dashboard →
    </a>
  </div>
  <p style="text-align:center;font-size:11px;color:#4b5563;margin-top:16px;">
    llm-guard-kit · <a href="{dashboard_url}/app/settings" style="color:#6b7280;">Unsubscribe</a>
  </p>
</body>
</html>"""
    return send_email(to, subject, body_html, user_configs=user_configs)


def test_run_email(
    to: str,
    test_set_name: str,
    pipeline_name: str,
    pass_rate: float,
    avg_risk: float,
    n_cases: int,
    run_id: int,
    dashboard_url: str = "https://app.llm-guard-kit.com",
    user_configs: dict | None = None,
) -> bool:
    """Send a test run completion email."""
    pass_pct = f"{pass_rate:.0%}"
    risk_pct = f"{avg_risk:.0%}"
    color = "#22c55e" if pass_rate >= 0.8 else "#f59e0b" if pass_rate >= 0.5 else "#ef4444"
    subject = f"[llm-guard-kit] Test run complete: {test_set_name} — {pass_pct} pass rate"
    body_html = f"""
<!DOCTYPE html>
<html>
<body style="font-family:sans-serif;background:#0f0f0f;color:#e5e7eb;padding:32px;">
  <div style="max-width:560px;margin:0 auto;background:#1f2937;border-radius:12px;padding:28px;border:1px solid #374151;">
    <h2 style="color:#f9fafb;margin:0 0 8px 0;">Regression Test Complete</h2>
    <p style="color:#9ca3af;font-size:14px;margin:0 0 24px 0;">
      Pipeline: <strong style="color:#e5e7eb">{pipeline_name}</strong> &nbsp;·&nbsp;
      Test Set: <strong style="color:#e5e7eb">{test_set_name}</strong>
    </p>
    <div style="display:flex;gap:16px;margin-bottom:24px;">
      <div style="flex:1;background:#111827;border-radius:8px;padding:16px;text-align:center;">
        <div style="font-size:28px;font-weight:bold;color:{color};">{pass_pct}</div>
        <div style="font-size:11px;color:#6b7280;margin-top:4px;">Pass Rate</div>
      </div>
      <div style="flex:1;background:#111827;border-radius:8px;padding:16px;text-align:center;">
        <div style="font-size:28px;font-weight:bold;color:#818cf8;">{risk_pct}</div>
        <div style="font-size:11px;color:#6b7280;margin-top:4px;">Avg Risk</div>
      </div>
      <div style="flex:1;background:#111827;border-radius:8px;padding:16px;text-align:center;">
        <div style="font-size:28px;font-weight:bold;color:#e5e7eb;">{n_cases}</div>
        <div style="font-size:11px;color:#6b7280;margin-top:4px;">Cases</div>
      </div>
    </div>
    <a href="{dashboard_url}/app/tests" style="display:inline-block;background:#4f46e5;color:#fff;
       text-decoration:none;padding:10px 20px;border-radius:8px;font-size:14px;font-weight:600;">
      View Results →
    </a>
  </div>
</body>
</html>"""
    return send_email(to, subject, body_html, user_configs=user_configs)
