# -*- coding: utf-8 -*-
"""本次刷新与上一版（备份）的差异摘要 + 关键口径校验。"""
import glob
import json
import os
from collections import Counter

D = '/Users/liuxinyuan/Desktop/Hermes输出-工作类/数据'


def load(p):
    with open(p, encoding='utf-8') as f:
        return json.load(f)


def newest(pattern):
    fs = sorted(glob.glob(os.path.join(D, pattern)))
    return fs[-1] if fs else None


# 客诉
comp = load(os.path.join(D, 'mcp_complaints.json'))['items']
bk = newest('_bak_complaints_pre_cron_*.json')
old = load(bk)['items'] if bk else []
old_ids = {i['id'] for i in old}
new_ids = {i['id'] for i in comp}
print('客诉: %d 条（旧 %d）新增 %d ｜ creator 缺 %d ｜ 黄明月/张立娅残留 %d'
      % (len(comp), len(old), len(new_ids - old_ids),
         sum(1 for i in comp if not i.get('creator')),
         sum(1 for i in comp if i.get('creator') in ('黄明月', '张立娅'))))
print('  状态分布: %s' % dict(Counter(i.get('status') for i in comp).most_common(6)))

# 客户
cust = load(os.path.join(D, 'mcp_customers.json'))
bk = newest('_bak_customers_pre26*.json')
oldc = load(bk)['customers'] if bk else []
old_names = {c.get('name') for c in oldc}
new_names = {c.get('name') for c in cust['customers']}
print('客户: %d 家（旧 %s）新增 %d ｜ group 已补 %d ｜ dept 已补 %d ｜ 金额>0 %d'
      % (len(cust['customers']), len(oldc) if oldc else '-', len(new_names - old_names),
         sum(1 for c in cust['customers'] if c.get('group')),
         sum(1 for c in cust['customers'] if c.get('dept')),
         sum(1 for c in cust['customers'] if (c.get('amount') or 0) > 0)))
print('  updated_at: %s' % cust.get('updated_at'))

# 活动 3a
act = load(os.path.join(D, 'activities_feishu.json'))
items = act['items']
print('活动3a activities_feishu: %d 条 ｜ 月份 %s ｜ 活动类型未填 %d'
      % (len(items), act.get('months'), sum(1 for i in items if i.get('channel') == 'none')))
print('  渠道: %s' % dict(Counter(i['channel'] for i in items)))
print('  归属人离职残留: %s' % Counter(i['submitted_by'] for i in items
                                   if i['submitted_by'] in ('黄明月', '张立娅')))

# 活动 3b
dly = load(os.path.join(D, 'daily_activities_mcp.json'))
print('活动3b daily_activities_mcp: 总 %d 条' % len(dly.get('items', [])))

# 订单
ordr = load(os.path.join(D, 'mcp_orders_input.json'))
dates = [str(o.get('创建时间'))[:10] for o in ordr if o.get('创建时间')]
print('订单: %d 条 ｜ 区间 %s ~ %s ｜ 月份 %s'
      % (len(ordr), min(dates), max(dates), dict(Counter(d[:7] for d in dates))))
print('  金额缺失: %d ｜ 下单人缺失: %d'
      % (sum(1 for o in ordr if not o.get('金额')), sum(1 for o in ordr if not o.get('创建者'))))
