"""Email HTML templates for all notification types.

Each template is a Python format string. Use render_template() to render.
"""

from html import escape

# ── Brand constants ──

BRAND_NAME = "OncoLit 肿瘤科研文献中心"
BRAND_COLOR = "#1a5276"
BASE_STYLE = """
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif; margin: 0; padding: 0; -webkit-font-smoothing: antialiased; }
@media only screen and (max-width: 600px) { .container { width: 100% !important; padding: 0 !important; } .header { padding: 12px !important; } .body { padding: 16px !important; } }
"""

# ── Reusable HTML fragments ──

_HEADER = """<div class="header" style="background:{brand_color};padding:20px;text-align:center;border-radius:8px 8px 0 0">
  <h2 style="color:#fff;margin:0;font-size:20px">{brand_name}</h2>
</div>"""

_FOOTER = """<div style="margin-top:24px;padding:16px;border-top:1px solid #eee;text-align:center">
  <p style="color:#999;font-size:11px;margin:4px 0">
    此邮件由系统自动发送。如不希望收到此类邮件，请
    <a href="{unsubscribe_url}" style="color:#1a5276">退订</a>。
  </p>
  <p style="color:#999;font-size:10px;margin:4px 0">© 2026 OncoLit Oncology. All rights reserved.</p>
</div>"""


def _render_digest_items(items: list[dict], emoji: str, border_color: str) -> str:
    """Render individual item blocks for the digest email."""
    html_parts = []
    for item in items:
        tags_str = " · ".join(
            escape(t.get("name_zh", "")) for t in (item.get("tags") or [])[:3]
        )
        journal = escape(item.get("journal", "") or "")
        author = escape(item.get("first_author", "") or "")
        title = escape(item.get("title", "") or "")
        html_parts.append(f"""<div style="border-left:3px solid {border_color};padding:8px 12px;margin:8px 0;background:#fafafa;border-radius:4px">
  <div style="font-weight:600;font-size:14px;margin-bottom:4px">{emoji} {title}</div>
  <div style="font-size:12px;color:#666">{author} et al. | <strong>{journal}</strong></div>
  {f'<div style="font-size:11px;color:#999;margin-top:4px">{tags_str}</div>' if tags_str else ''}</div>""")
    return "\n".join(html_parts)


# ── Templates ──

DIGEST_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
<style>{base_style}</style></head>
<body style="margin:0;padding:0;background:#f4f6f8">
<div class="container" style="max-width:600px;margin:0 auto;padding:16px">
{header}
<div class="body" style="background:#fff;padding:20px;border:1px solid #eee;border-top:none;border-radius:0 0 8px 8px">
  <p style="font-size:15px;color:#333;margin:0 0 16px">👋 {user_name}，早上好！今天为你准备了以下肿瘤学最新文献：</p>
  {summary_line}
  {must_read_items}
  {recommended_items}
  <div style="text-align:center;margin-top:24px">
    <a href="{base_url}/app/feed" style="display:inline-block;background:{brand_color};color:#fff;padding:10px 32px;border-radius:6px;text-decoration:none;font-size:14px">查看全部文献 →</a>
  </div>
</div>
{footer}
</div></body></html>"""

INVITE_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
<style>{base_style}</style></head>
<body style="margin:0;padding:0;background:#f4f6f8">
<div class="container" style="max-width:500px;margin:0 auto;padding:16px">
{header}
<div class="body" style="background:#fff;padding:24px;border:1px solid #eee;border-top:none;border-radius:0 0 8px 8px;text-align:center">
  <h3 style="margin:0 0 8px">{inviter_name} 邀请你加入</h3>
  <p style="font-size:18px;font-weight:600;color:{brand_color};margin:0 0 16px">{team_name}</p>
  <p style="color:#666;font-size:14px;line-height:1.6">加入后，你可以查看科室共享的文献、参与讨论、使用团队协作功能。</p>
  <a href="{invite_link}" style="display:inline-block;background:{brand_color};color:#fff;padding:12px 40px;border-radius:6px;text-decoration:none;font-size:16px;margin-top:12px">接受邀请 →</a>
</div>
{footer}
</div></body></html>"""

PASSWORD_RESET_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
<style>{base_style}</style></head>
<body style="margin:0;padding:0;background:#f4f6f8">
<div class="container" style="max-width:500px;margin:0 auto;padding:16px">
{header}
<div class="body" style="background:#fff;padding:24px;border:1px solid #eee;border-top:none;border-radius:0 0 8px 8px">
  <p style="font-size:15px;color:#333">Hi {user_name}，</p>
  <p style="color:#666;font-size:14px;line-height:1.6">我们收到了你的密码重置请求。点击下方按钮设置新密码：</p>
  <div style="text-align:center;margin:24px 0">
    <a href="{reset_link}" style="display:inline-block;background:{brand_color};color:#fff;padding:12px 40px;border-radius:6px;text-decoration:none;font-size:16px">重置密码</a>
  </div>
  <p style="color:#999;font-size:12px">此链接 1 小时内有效。如果你没有请求重置密码，请忽略此邮件。</p>
</div>
{footer}
</div></body></html>"""

NOTIFICATION_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
<style>{base_style}</style></head>
<body style="margin:0;padding:0;background:#f4f6f8">
<div class="container" style="max-width:500px;margin:0 auto;padding:16px">
{header}
<div class="body" style="background:#fff;padding:24px;border:1px solid #eee;border-top:none;border-radius:0 0 8px 8px">
  <p style="font-size:15px;color:#333">Hi {user_name}，</p>
  <div style="color:#666;font-size:14px;line-height:1.6">{content}</div>
  {cta_html}
</div>
{footer}
</div></body></html>"""

VERIFICATION_CODE_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
<style>{base_style}</style></head>
<body style="margin:0;padding:0;background:#f4f6f8">
<div class="container" style="max-width:500px;margin:0 auto;padding:16px">
{header}
<div class="body" style="background:#fff;padding:24px;border:1px solid #eee;border-top:none;border-radius:0 0 8px 8px;text-align:center">
  <p style="font-size:15px;color:#333">{user_name}，你好：</p>
  <p style="color:#666;font-size:14px;line-height:1.6">请使用以下验证码完成邮箱验证：</p>
  <div style="background:#f5f8fc;border-radius:8px;padding:16px;margin:16px 0;letter-spacing:8px;font-size:32px;font-weight:700;color:#1a5276;font-family:monospace">{code}</div>
  <p style="color:#999;font-size:12px">验证码 {minutes} 分钟内有效。如非本人操作请忽略此邮件。</p>
</div>
{footer}
</div></body></html>"""

TEMPLATES = {
    "digest": DIGEST_TEMPLATE,
    "invite": INVITE_TEMPLATE,
    "password_reset": PASSWORD_RESET_TEMPLATE,
    "notification": NOTIFICATION_TEMPLATE,
    "verification_code": VERIFICATION_CODE_TEMPLATE,
}


def render_template(name: str, **kwargs) -> str:
    """Render a named template with the given variables.

    All templates receive base_style, header, footer, brand_color, brand_name
    automatically.  Pass additional template-specific kwargs.
    """
    tpl = TEMPLATES.get(name)
    if not tpl:
        raise ValueError(f"Unknown template: {name}")

    base_url = kwargs.pop("base_url", "")
    unsubscribe_url = f"{base_url}/app/settings/notifications"

    context = {
        "base_style": BASE_STYLE,
        "brand_color": BRAND_COLOR,
        "brand_name": BRAND_NAME,
        "header": _HEADER.format(brand_color=BRAND_COLOR, brand_name=BRAND_NAME),
        "footer": _FOOTER.format(unsubscribe_url=unsubscribe_url),
        "base_url": base_url,
        "unsubscribe_url": unsubscribe_url,
        **kwargs,
    }

    # Build optional CTA HTML for notification template
    if "cta_text" in context and "cta_link" in context and context["cta_text"]:
        context["cta_html"] = (f'<div style="text-align:center;margin:20px 0">'
                              f'<a href="{context["cta_link"]}" style="display:inline-block;'
                              f'background:{BRAND_COLOR};color:#fff;padding:10px 32px;'
                              f'border-radius:6px;text-decoration:none;font-size:14px">'
                              f'{context["cta_text"]} →</a></div>')
    else:
        context["cta_html"] = ""

    return tpl.format(**context)
