#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""按 2026-09-20 大客户分派结果，刷新「客户特殊需求」数据 + 大客户1/2 专版复核页。

背景：
  · customer_special_requirements.json（工作台 Tab 用，2865 条）里 owner 仍挂在改派前的销售员上。
  · sr_review_kac.json / 工具/特殊要求复核-大客户.html 生成于 16:37，早于 22:47 的分派落地，
    仍包含已调出的「迈克生物」等客户。
做法：
  ① 用当前归属映射（_cust_sp.json 优先 → 客户区域销售对应清单_诊断.csv 兜底）回填两个数据集的
     owner / activity_owner / salesperson。
  ② 大客户专版 = 客户归属 ∈ {大客户1, 大客户2} 的行（即 刘子研 / 赵云浩 名下）。
  ③ 重新生成两份复核页。
"""
import json, io, os, csv, shutil

ROOT = '/Users/liuxinyuan/Desktop/Hermes输出-工作类'
BAK = '.bak_before_ka_sr_refresh_20260920'

def p(*a): return os.path.join(ROOT, *a)
def backup(rel):
    if os.path.exists(p(rel)) and not os.path.exists(p(rel) + BAK):
        shutil.copy(p(rel), p(rel) + BAK)

# ── 当前归属（改派后） ──
cs = json.load(io.open(p('数据/pricing/_cust_sp.json'), encoding='utf-8'))
rows = list(csv.DictReader(io.open(p('数据/客户区域销售对应清单_诊断.csv'), encoding='utf-8-sig')))
area = {r['客户']: r['区域'] for r in rows}
owner_csv = {r['客户']: r['销售员'] for r in rows}
KA_AREAS = {'大客户1', '大客户2'}
def cur_owner(cust):
    return cs.get(cust) or owner_csv.get(cust) or ''
def is_ka(cust):
    return area.get(cust) in KA_AREAS

# ── ① 工作台 Tab 数据 ──
backup('数据/customer_special_requirements.json')
d = json.load(io.open(p('数据/customer_special_requirements.json'), encoding='utf-8'))
fixed = 0
for x in d['items']:
    o = cur_owner(x.get('customer') or '')
    if o and x.get('owner') != o:
        x['owner'] = o
        x['note'] = (x.get('note') or '') + '｜2026-09-20 分派：归属更新为 %s' % o
        fixed += 1
d['updated_at'] = '2026-09-20 23:40:00'
io.open(p('数据/customer_special_requirements.json'), 'w', encoding='utf-8').write(
    json.dumps(d, ensure_ascii=False, indent=1))
print('  ① customer_special_requirements.json：owner 更正 %d 条' % fixed)

# ── ② 复核数据集 ──
backup('数据/sr_review.json')
sr = json.load(io.open(p('数据/sr_review.json'), encoding='utf-8'))
srrows = sr if isinstance(sr, list) else sr.get('rows', [])
chg = 0
for r in srrows:
    o = cur_owner(r.get('customer') or '')
    if o and r.get('activity_owner') != o:
        r['activity_owner'] = o
        r['salesperson'] = o
        chg += 1
io.open(p('数据/sr_review.json'), 'w', encoding='utf-8').write(json.dumps(sr, ensure_ascii=False, indent=1))
print('  ② sr_review.json：归属更正 %d 行' % chg)

# ── ③ 大客户1/2 专版数据集 ──
ka = [dict(r) for r in srrows if is_ka(r.get('customer') or '')]
backup('数据/sr_review_kac.json')
io.open(p('数据/sr_review_kac.json'), 'w', encoding='utf-8').write(json.dumps(ka, ensure_ascii=False, indent=1))
from collections import Counter
print('  ③ sr_review_kac.json：%d 行 / %d 客户' % (len(ka), len({r['customer'] for r in ka})))
print('     按销售员:', Counter(r.get('activity_owner') for r in ka).most_common())
_bp = p('数据/sr_review_kac.json') + BAK
if os.path.exists(_bp):
    _bd = json.load(io.open(_bp, encoding='utf-8'))
    _brows = _bd.get('rows', []) if isinstance(_bd, dict) else _bd
else:
    _brows = []
gone = [c for c in {r.get('customer','') for r in _brows} if c and not is_ka(c)]
print('     已移出(不再是1/2岗):', gone)
