#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
把结构化促销方案合并进 数据/promo_campaigns.json 的 programs 字段
（供 ai_chat.py 的 _promo_lines() 渲染进 system prompt）

源：
  开学季促销方案_spec.json（生命科学部 9月预付款促销，7 档位）
出：数据/promo_campaigns.json → + programs[]
"""
import json
import os

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA = os.path.join(ROOT, '数据')
SPEC = os.path.join(ROOT, '开学季促销方案_spec.json')

progs = []

# ── 1. 生命科学部 9月开学季预付款促销（来自 spec.json 的档位表）──
try:
    spec = json.load(open(SPEC, encoding='utf-8'))
    tiers, boosters, compliance, goal = [], [], [], ''
    for b in spec.get('blocks', []):
        if b.get('type') == 'table' and '档位' in (b.get('header') or []) and '赠品价值' in (b.get('header') or [])[1]:
            for r in b.get('rows', []):
                if len(r) >= 4 and r[0]:
                    tiers.append({'tier': r[0], 'value': r[1], 'main': r[2], 'alt': r[3]})
        if b.get('type') == 'bullet_list':
            for it in b.get('items', []) or []:
                if '活动时间' in it:
                    pass
                if '核心目标' in it:
                    goal = it.split('：', 1)[-1]
        if b.get('type') == 'numbered_list':
            for it in b.get('items', []) or []:
                if len(compliance) < 4 and ('合规' in it or '购物卡' in it or '签收' in it):
                    compliance.append(it)
                elif '新客首单' in it or '转介绍' in it or '晒单' in it or '大礼包' in it:
                    boosters.append(it)
    if tiers:
        progs.append({
            'id': 'ls_202609_prepay',
            'line': 'ls',
            'lines': ['ls'],
            'name': '9月开学季·预付款赠礼',
            'start': '2026-09-01', 'end': '2026-09-30',
            'goal': goal or '新客扩面、老客口碑；低门槛档位为主力获客引擎',
            'object': '生命科学销售部全部客户（高校、科研院所课题组）',
            'tiers': tiers,
            'boosters': boosters,
            'compliance': compliance,
            'source': '开学季促销方案_spec.json',
        })
except Exception as e:
    print('⚠ spec 解析失败：', e)

# ── 2. 科研产品开学季打包促销（来自 xlsx 的「产品打包推广」表）──
try:
    src = json.load(open(os.path.join(DATA, 'promo_campaigns.json'), encoding='utf-8'))
    for c in src.get('campaigns', []):
        if c.get('sheet') == '产品打包推广':
            packs = []
            cur = None
            for r in c.get('rows', []):
                if not r or not r[0]:
                    continue
                if len(r) >= 3 and r[1] and not r[1].startswith('BR'):
                    cur = {'app': r[0], 'items': []}
                    packs.append(cur)
                    rest = r[1:]
                else:
                    rest = r
                if cur is None:
                    cur = {'app': r[0], 'items': []}
                    packs.append(cur)
                    rest = r[1:]
                for i in range(0, len(rest) - 1, 2):
                    nm, sk = rest[i], rest[i + 1]
                    if nm and sk and str(sk).startswith('BR'):
                        cur['items'].append('%s（%s）' % (nm, sk))
                if len(rest) >= 2 and str(rest[-1]).startswith('BR') and len(rest) % 2 == 1:
                    pass
            packs = [p for p in packs if p['items']]
            if packs:
                progs.append({
                    'id': 'ls_202609_pack',
                    'line': 'ls', 'lines': ['ls'],
                    'name': '科研产品开学季打包促销方案',
                    'start': '2026-09-01', 'end': '2026-09-30',
                    'goal': '按应用场景打包主推，提高客单价与渗透率',
                    'object': '高校/科研院所课题组',
                    'packs': [{'app': p['app'], 'items': p['items']} for p in packs],
                    'source': c.get('file', ''),
                })
except Exception as e:
    print('⚠ 打包方案解析失败：', e)

# ── 合并写回 ──
path = os.path.join(DATA, 'promo_campaigns.json')
d = json.load(open(path, encoding='utf-8'))
old = {p.get('id') for p in (d.get('programs') or [])}
d['programs'] = [p for p in (d.get('programs') or []) if p.get('id') not in {x['id'] for x in progs}] + progs
d['programs'] = progs
json.dump(d, open(path, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)

print('programs 写入:', len(progs), '个')
for p in progs:
    print(' -', p['id'], '|', p['name'], '| 档位', len(p.get('tiers') or []),
          '| 打包', len(p.get('packs') or []), '| 加码', len(p.get('boosters') or []),
          '| 合规', len(p.get('compliance') or []))
print('→', path)
