#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
宝锐品牌套件 —— Logo + Slogan 标准（唯一权威实现）
================================================================
【铁律】所有对外物料与工作文档（HTML/PDF）必须含 Logo + slogan。
本模块是唯一实现，任何生成器都从这里取，不得各写一份。

  页眉：Logo（base64 内联）+ BIORI BIOTECH + 宝锐生物 + 标签 + 【slogan】
  页脚：BIORI BIOTECH · 宝锐生物 ｜ 电话 ｜ 网址 ｜ 邮箱 ｜ 地址  + 【slogan】

用法（生成器里）：
    import brand_kit as BK
    html = BK.inject(html, theme='dark', tag='营销中心', footer_extra='...')
    # 幂等：重复调用不会叠两套

自检：
    python3 brand_kit.py --verify 文件.html      # 单文件
    python3 brand_kit.py --selftest              # 模块自检
"""
import base64
import io
import os
import re
import sys

# ── 品牌常量（改这里，全公司生效）────────────────────────────
SLOGAN = '守护生命健康，缔造美好生活'
BRAND_EN = 'BIORI BIOTECH'
BRAND_CN = '宝锐生物'
TEL = '0756-8699969'
SITE = 'www.biori.com'
MAIL = 'marketing@biori.com'
ADDR = '珠海市香洲区水岸一路88号'

LOGO_SRC = os.path.expanduser('~/work/公司资料/logo_transparent.png')
MARKS = ('bior-brand-v1', 'bior-header', 'bior-slogan')   # 幂等锚点
SLOGAN_KEY = '守护生命健康'          # 校验用的短特征串

# 页眉高度：logo 显示 36px，2x 图 72px
LOGO_H = 72
_logo_cache = {}


def logo_data_uri(h=LOGO_H):
    """返回 logo 的 data URI（缩放到高度 h，PNG 优化）。结果缓存。"""
    if h in _logo_cache:
        return _logo_cache[h]
    try:
        from PIL import Image
    except ImportError:
        raise RuntimeError('需要 Pillow：/usr/bin/python3 -m pip install pillow')
    if not os.path.exists(LOGO_SRC):
        raise FileNotFoundError('Logo 源文件不存在：%s' % LOGO_SRC)
    im = Image.open(LOGO_SRC).convert('RGBA')
    w, hh = im.size
    nw = int(round(w * h / hh))
    im = im.resize((nw, h), Image.LANCZOS)
    buf = io.BytesIO()
    im.save(buf, format='PNG', optimize=True)
    uri = 'data:image/png;base64,' + base64.b64encode(buf.getvalue()).decode()
    _logo_cache[h] = uri
    return uri


# ── CSS ───────────────────────────────────────────────────────
CSS = """
/* ===== bior-brand-v1 · 宝锐品牌标准（Logo+Slogan）===== */
.bior-header{background:linear-gradient(135deg,#0d47a1 0%,#1565c0 50%,#1a73e8 100%);color:#fff;
  box-shadow:0 2px 8px rgba(13,71,161,.18);
  font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif}
.bior-header-inner{max-width:1560px;margin:0 auto;display:flex;align-items:center;gap:13px;padding:10px 22px}
.bior-logo-chip{background:#fff;border-radius:8px;padding:3px 10px;display:flex;align-items:center;
  box-shadow:0 1px 3px rgba(0,0,0,.16);flex:none}
.bior-logo-chip img{height:34px;width:auto;display:block}
.bior-brand{line-height:1.24;flex:none}
.bior-name{font-size:15px;font-weight:700;letter-spacing:.6px;display:block}
.bior-cn{font-size:11px;opacity:.86;display:block;letter-spacing:1.5px}
.bior-tagwrap{margin-left:auto;text-align:right;line-height:1.3;flex:none}
.bior-tag{font-size:11px;opacity:.85;display:block}
.bior-slogan{font-size:13.5px;font-weight:600;letter-spacing:2px;display:block;
  text-shadow:0 1px 2px rgba(0,0,0,.13)}
.bior-footer{background:#0d2a52;color:#c9d8ee;padding:15px 22px;text-align:center;line-height:1.9;
  font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif}
.bior-footer-slogan{font-size:14px;font-weight:700;letter-spacing:3px;color:#fff;margin-bottom:5px}
.bior-footer-meta{font-size:11px;opacity:.8}
.bior-footer-meta b{font-weight:600;color:#fff;opacity:.95}
.bior-footer-extra{font-size:10.5px;opacity:.6;margin-top:5px}
/* 白底顶栏变体（工作台页面） */
.bior-header.light{background:#fff;border-bottom:1px solid #e0e0e0;box-shadow:0 1px 4px rgba(0,0,0,.06)}
.bior-header.light .bior-name{color:#1852B6}
.bior-header.light .bior-cn{color:#5f6368;opacity:1}
.bior-header.light .bior-tag{color:#9aa0a6;opacity:1}
.bior-header.light .bior-slogan{color:#1565c0;text-shadow:none}
.bior-header.light .bior-logo-chip{box-shadow:none;padding:0;background:transparent;border-radius:0}
@media(max-width:760px){
  .bior-slogan{font-size:11px;letter-spacing:1px}
  .bior-header-inner{gap:9px;padding:9px 13px}
  .bior-logo-chip img{height:26px}
}
@media print{.bior-footer{background:#0d2a52 !important;-webkit-print-color-adjust:exact;print-color-adjust:exact}}
"""


def header_html(theme='dark', tag='营销中心'):
    """页眉：Logo + 品牌名 + 标签 + slogan。theme='dark'|'light'"""
    cls = 'bior-header' + ('' if theme == 'dark' else ' light')
    return (
        '<div class="%s" data-bior-brand="1">'
        '<div class="bior-header-inner">'
        '<div class="bior-logo-chip"><img src="%s" alt="%s"></div>'
        '<div class="bior-brand">'
        '<span class="bior-name">%s</span>'
        '<span class="bior-cn">%s</span>'
        '</div>'
        '<div class="bior-tagwrap">'
        '<span class="bior-tag">%s</span>'
        '<span class="bior-slogan">%s</span>'
        '</div>'
        '</div></div>'
    ) % (cls, logo_data_uri(), BRAND_EN, BRAND_EN, BRAND_CN, tag, SLOGAN)


def footer_html(extra='', contact=True):
    """页脚落款：slogan + 品牌 + 联系方式。"""
    if contact:
        meta = ('<b>%s</b> · %s ｜ 电话 %s ｜ %s ｜ %s ｜ %s'
                % (BRAND_EN, BRAND_CN, TEL, SITE, MAIL, ADDR))
    else:
        meta = '<b>%s</b> · %s' % (BRAND_EN, BRAND_CN)
    xs = '<div class="bior-footer-extra">%s</div>' % extra if extra else ''
    return (
        '<div class="bior-footer" data-bior-brand="1">'
        '<div class="bior-footer-slogan">%s</div>'
        '<div class="bior-footer-meta">%s</div>%s'
        '</div>'
    ) % (SLOGAN, meta, xs)


def head_block(theme='dark', tag='营销中心'):
    """返回 (css, html)。注入到 <head> 前请自行包 <style>。"""
    return CSS, header_html(theme, tag)


# ── 幂等注入 ──────────────────────────────────────────────────
def _has_header(html):
    """⚠️ 必须匹配【元素】而非类名：CSS 里有 .bior-header{...}，
       用 'bior-header' in html 会在注入 CSS 后误判为「已有页眉」→ 页眉 HTML 永不写入。"""
    return 'class="bior-header' in html


def _has_footer(html):
    """同上：CSS 里有 .bior-footer{...}。"""
    return 'class="bior-footer' in html


def _has_slogan(html):
    return SLOGAN_KEY in html


def inject(html, theme='dark', tag='营销中心', footer=True, footer_extra='',
           ensure_css=True, ensure_slogan=True):
    """
    幂等注入品牌页眉/页脚。重复调用不叠加。
      theme='dark'  工业蓝渐变（对外交付件默认）
      theme='light' 白色顶栏（工作台页面）
    """
    out = html

    # ① CSS
    if ensure_css and 'bior-brand-v1' not in out:
        style = '\n<style>\n%s\n</style>\n' % CSS
        if '</head>' in out:
            out = out.replace('</head>', style + '</head>', 1)
        else:
            out = style + out

    # ② 页眉
    if not _has_header(out):
        hb = header_html(theme, tag)
        m = re.search(r'<body[^>]*>', out, re.I)
        if m:
            out = out[:m.end()] + '\n' + hb + out[m.end():]
        else:
            out = hb + '\n' + out

    # ③ 兜底：有页眉但无 slogan（老页面）→ 把 slogan 塞进 tagwrap
    if ensure_slogan and not _has_slogan(out):
        if 'class="bior-tagwrap"' in out:
            out = re.sub(r'(<span class="bior-tag">[^<]*</span>)',
                         r'\1<span class="bior-slogan">%s</span>' % SLOGAN,
                         out, count=1)
        if not _has_slogan(out) and '</body>' in out:
            out = out.replace('</body>', '<div class="bior-slogan">%s</div>\n</body>' % SLOGAN, 1)

    # ④ 页脚
    if footer and not _has_footer(out):
        fb = footer_html(footer_extra)
        if '</body>' in out:
            out = out.replace('</body>', fb + '\n</body>', 1)
        else:
            out = out + fb
    return out


# ── 自检 ──────────────────────────────────────────────────────
def verify(html):
    """返回自检清单 dict。"""
    return {
        'logo': 'data:image/png;base64' in html,
        '品牌英文': BRAND_EN in html,
        '品牌中文': BRAND_CN in html,
        'slogan': SLOGAN_KEY in html,
        '页眉': 'bior-header' in html,
        '页脚': 'bior-footer' in html,
        '联系方式': TEL in html,
        '禁用占位符': not re.search(r'\{\{[A-Z_]+\}\}|\{LOGO_B64\}|\{SLOGAN\}', html),
    }


def check_file(path):
    with io.open(path, encoding='utf-8', errors='ignore') as f:
        return verify(f.read())


if __name__ == '__main__':
    if '--selftest' in sys.argv:
        h = '<html><head></head><body><h1>测试</h1></body></html>'
        a = inject(h, tag='营销中心')
        b = inject(a, tag='营销中心')          # 幂等复跑
        assert a == b, '❌ 注入不幂等'
        v = verify(a)
        assert all(v.values()), '❌ 自检未过: %s' % v
        print('✅ brand_kit 自检通过（幂等 + 6 项齐备）')
        print('   header 长度 %d 字符，CSS %d 字符' % (len(header_html()), len(CSS)))
        for k, ok in v.items():
            print('   %s %s' % ('✅' if ok else '❌', k))
    elif '--verify' in sys.argv:
        for p in sys.argv[2:]:
            v = check_file(p)
            bad = [k for k, ok in v.items() if not ok]
            print('%s %s %s' % ('✅' if not bad else '❌', os.path.basename(p),
                                '' if not bad else '缺: ' + ', '.join(bad)))
    else:
        print(__doc__)
