# -*- coding: utf-8 -*-
"""按官方《诊断原料&生命科学客户清单》校正权限表 pricing/_key_customers.json

- 客户条目：以官方清单的销售员为准（含去地区后缀别名匹配）
- 集团聚合条目（如"圣湘集团"）：官方清单里该集团成员销售员唯一时同步，多人时保留并报告
- 不改数量、不改其他字段；先备份

用法：/usr/bin/python3 脚本/align_key_customers.py [--apply]
"""
import json, os, shutil, sys, datetime, collections

B = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
KC = os.path.join(B, '数据', 'pricing', '_key_customers.json')
PRICING = os.path.join(B, '数据', 'pricing')
APPLY = '--apply' in sys.argv


def strip_sfx(n):
    import re
    return re.sub(r'-(浙江|广东|江苏|北京|上海|华北|华南|华中|华东|华西|山东|四川|福建|河南|河北|湖南|湖北|安徽|重庆|天津|陕西)$',
                  '', (n or '').strip())


au = json.load(open(sorted(f"{PRICING}/{f}" for f in os.listdir(PRICING)
                           if f.startswith('_auth_customers_'))[-1], encoding='utf-8'))
auth = {k: v['sp'] for k, v in au['customers'].items()}
groups = au['groups']

kc = json.load(open(KC, encoding='utf-8'))
fixes, group_fix, group_multi, unmatched = [], [], [], []

for e in kc:
    nm = (e.get('name') or '').strip()
    cur = (e.get('salesperson') or '').strip()
    tgt = auth.get(nm) or auth.get(strip_sfx(nm))
    if tgt:
        if cur != tgt:
            fixes.append((nm, cur, tgt, e.get('total') or 0))
        continue
    g = groups.get(nm)                       # 集团聚合条目
    if g:
        sps = [s for s in g['sp'] if s]
        if len(sps) == 1 and cur != sps[0]:
            group_fix.append((nm, cur, sps[0], len(g['members'])))
        elif len(sps) > 1:
            group_multi.append((nm, cur, sps))
        continue
    if cur:
        unmatched.append((nm, cur, e.get('total') or 0))

print(f"权限表 {len(kc)} 条 / 官方清单 {len(auth)} 客户 + {len(groups)} 集团\n")
print(f"① 客户条目需校正: {len(fixes)} 条（涉及累计 {sum(f[3] for f in fixes)/10000:.1f}万）")
for nm, cur, tgt, t in sorted(fixes, key=lambda x: -x[3]):
    print(f"   {nm[:34]:36s} {cur or '(空)':8s} → {tgt:8s}  {t/10000:>8.1f}万")
print(f"\n② 集团聚合条目需校正(成员销售员唯一): {len(group_fix)} 条")
for nm, cur, tgt, nm2 in group_fix:
    print(f"   {nm[:20]:22s} {cur or '(空)':8s} → {tgt:8s}  ({nm2} 个成员)")
print(f"\n③ 集团成员跨多人(保留不动): {len(group_multi)} 条")
for nm, cur, sps in group_multi[:12]:
    print(f"   {nm[:20]:22s} 现={cur or '(空)':8s} 成员归属={sps}")
print(f"\n④ 官方清单里查不到、权限表却有归属: {len(unmatched)} 条")
for nm, cur, t in sorted(unmatched, key=lambda x: -x[2])[:12]:
    print(f"   {nm[:34]:36s} {cur:8s}  {t/10000:>8.1f}万")

if not APPLY:
    print("\n[预演] 未写入。加 --apply 落地。")
    sys.exit(0)

ts = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
bdir = os.path.join(B, '备份', f'归属校正_{ts}')
os.makedirs(bdir, exist_ok=True)
shutil.copy2(KC, os.path.join(bdir, '_key_customers.json'))

patch = {nm: tgt for nm, _, tgt, _ in fixes}
patch.update({nm: tgt for nm, _, tgt, _ in group_fix})
for e in kc:
    nm = (e.get('name') or '').strip()
    if nm in patch:
        e['sales'] = patch[nm]
        e['salesperson'] = patch[nm]

with open(KC, 'w', encoding='utf-8') as f:
    json.dump(kc, f, ensure_ascii=False, indent=2)

print(f"\n✅ 已写入 {len(patch)} 处校正；备份 {os.path.relpath(bdir, B)}/")
per = collections.Counter(e.get('salesperson') for e in kc)
print("   校正后分布:", dict(per.most_common()))
