#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""按用户指定校正 _key_customers.json 中的集团级归属（仅 2 条）。

用户指令：圣湘集团→赵云浩；东方基因集团→刘子研。其他不动。
集团条目 = 集团级归属（与成员并集分开），build_customer_360.py 的 group_owner() 消费它。
"""
import json, os, re, shutil, sys, time

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
P = os.path.join(ROOT, '数据/pricing/_key_customers.json')

FIX = {'圣湘集团': '赵云浩', '东方基因集团': '刘子研'}

raw = open(P, encoding='utf-8').read()
# 探测原有格式，落盘时保持一致，避免整文件 diff
m_ind = re.search(r'\n(\s+)"name"', raw)
indent = len(m_ind.group(1)) if m_ind else 2
ascii_ = '\\u' in raw and not re.search(r'[\u4e00-\u9fff]', raw)
print(f'原格式: indent={indent} ensure_ascii={ascii_}  size={len(raw)}')

data = json.loads(raw)
if isinstance(data, dict):
    data = list(data.values())

hits = []
for e in data:
    nm = str(e.get('name', ''))
    if nm in FIX:
        old = e.get('salesperson') or e.get('sales')
        new = FIX[nm]
        if old != new:
            hits.append((nm, old, new))
            for k in ('sales', 'salesperson'):
                if k in e:
                    e[k] = new

if not hits:
    print('无需修改')
    sys.exit(0)

print('待改:')
for nm, old, new in hits:
    print(f'   {nm}: {old} → {new}')

if '--apply' not in sys.argv:
    print('\n[dry-run] 加 --apply 落盘')
    sys.exit(0)

bk = os.path.join(ROOT, '备份', f'权限表集团归属_{time.strftime("%Y%m%d_%H%M%S")}')
os.makedirs(bk, exist_ok=True)
shutil.copy2(P, os.path.join(bk, '_key_customers.json'))

with open(P, 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=ascii_, indent=indent)
    f.write('\n')

# 回读校验
chk = json.load(open(P, encoding='utf-8'))
if isinstance(chk, dict):
    chk = list(chk.values())
for nm, old, new in hits:
    cur = [e for e in chk if str(e.get('name')) == nm][0]
    assert cur.get('salesperson') == new and cur.get('sales') == new, nm
print(f'\n✅ 已落盘 {len(hits)} 条  备份={bk}  条目数={len(chk)}（应保持 {len(data)}）')
