#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""从飞书活动库挖「竞品证据」，按货号归档（只摘录原文，不改写、不推断）。

背景：诊断原料线**没有**货号级竞品对标表（现有竞品大表是生命科学线 BR 系列）。
替代做法：用 6,251 条活动记录里的真实提及，形成「该货号 → 客户在用哪些竞品 → 原文证据」。
"""
import json
import os
import re
from collections import Counter, defaultdict

ROOT = '/Users/liuxinyuan/Desktop/Hermes输出-工作类'
CORE = os.path.join(ROOT, '数据/diag_sku_core.json')
ACT = os.path.join(ROOT, '数据/activities_feishu.json')

BRANDS = ['诺唯赞', '翌圣', '菲鹏', '瀚海新酶', '瀚海', '全式金', '康为世纪', '康为', '宝创', '致善',
          '迈迪安', '赛默飞', 'Thermo', 'Takara', '宝生物', '近岸', '义翘', '金斯瑞', '吐露港',
          '艾科瑞', 'ABclonal', '爱博泰克', 'Toyobo', 'NEB', 'Roche', '罗氏', '普洛麦格', 'Promega',
          'Sigma', 'Merck', '默克', '碧云天', '生工', '擎科', '华大', '翊圣']


def brand_of(text):
    return [b for b in BRANDS if b in text]


def name_tokens(rec):
    """从品名里取有辨识度的英文/中文关键词，用于活动文本匹配。"""
    toks = set()
    for src in (rec.get('品名') or '', rec.get('品名内') or ''):
        for m in re.findall(r'[A-Za-z][A-Za-z0-9®™\-]{3,}', src):
            t = m.strip('-').lower()
            if t not in ('plus', 'probe', 'premix', 'master', 'mix', 'series', 'for', 'with', 'and'):
                toks.add(t)
        for m in re.findall(r'[\u4e00-\u9fff]{2,6}(?:酶|预混|保护剂|缓冲液|试剂)', src):
            toks.add(m)
    return {t for t in toks if len(t) >= 3}


def main():
    core = json.load(open(CORE, encoding='utf-8'))
    acts = json.load(open(ACT, encoding='utf-8'))['items']
    brand_global = Counter()
    for a in acts:
        for b in brand_of(str(a.get('text') or '') + str(a.get('type') or '')):
            brand_global[b] += 1

    hit = 0
    for rec in core['items']:
        sku = rec['货号']
        toks = name_tokens(rec)
        ev, brand_cnt = [], Counter()
        for a in acts:
            txt = str(a.get('text') or '') + ' ' + str(a.get('type') or '')
            bk = brand_of(txt)
            if not bk:
                continue
            low = txt.lower()
            matched = sku.lower() in low or any(t in low for t in toks)
            if not matched:
                continue
            brand_cnt.update(bk)
            if len(ev) < 12:
                ev.append({'日期': a.get('date'), '客户': a.get('customer'), '销售': a.get('sales'),
                           '竞品': bk, '原文': re.sub(r'\s+', ' ', txt)[:160]})
        rec['竞品证据'] = ev
        rec['竞品品牌热度'] = dict(brand_cnt.most_common(8))
        rec['匹配用关键词'] = sorted(toks)[:8]
        if ev:
            hit += 1

    core['竞品口径'] = ('诊断原料线无货号级竞品对标表；本字段为「活动库真实提及」证据（客户/日期/原文可溯源），'
                   '非产品参数级对比。可用竞品情报卡（核心竞品6家）作公司级补充。')
    core['竞品品牌总热度'] = dict(brand_global.most_common(20))
    core['统计']['有竞品证据的货号'] = hit
    json.dump(core, open(CORE, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
    print('核心货号 %d 个 ｜ 挖到竞品证据的 %d 个' % (len(core['items']), hit))
    print('活动库品牌总热度 TOP10:', list(brand_global.most_common(10)))
    print()
    for rec in core['items']:
        if rec.get('竞品证据'):
            print('  %-12s %s ｜ 证据 %d 条 ｜ %s' % (
                rec['货号'], (rec.get('品名') or rec.get('品名内') or '')[:34],
                len(rec['竞品证据']), rec['竞品品牌热度']))
    print('\n→ 已写回', CORE)


if __name__ == '__main__':
    main()
