#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""活动数据：归属人离职归并（沿用 cron Step 1 既有规则：黄明月/张立娅→刘子研）。

1) 就地重写 数据/activities_feishu.json 的 submitted_by/sales
2) 从 dept_overrides.json 移除已归并的人（不再需要单独部门）
3) 报告归并前后
"""
import io
import json
import os
from collections import Counter

ROOT = '/Users/liuxinyuan/Desktop/Hermes输出-工作类'
OWNER_MERGE = {'张立娅': '刘子研', '黄明月': '刘子研'}      # 与 cron 刷新任务 Step 1 同口径

f = os.path.join(ROOT, '数据', 'activities_feishu.json')
d = json.load(io.open(f, encoding='utf-8'))
items = d['items']
before = Counter(x['submitted_by'] for x in items)
moved = Counter()
for x in items:
    src = (x.get('submitted_by') or '').strip()
    n = OWNER_MERGE.get(src)
    if n:
        moved['%s→%s' % (src, n)] += 1
        x['owner_merged_from'] = src
        x['submitted_by'] = n
        x['sales'] = n
d['owner_merge'] = OWNER_MERGE
d['owner_merge_applied'] = {k: v for k, v in moved.items()}
io.open(f, 'w', encoding='utf-8').write(json.dumps(d, ensure_ascii=False, indent=0))

ov_f = os.path.join(ROOT, '数据', 'dept_overrides.json')
ov = json.load(io.open(ov_f, encoding='utf-8'))
removed = [k for k in OWNER_MERGE if k in ov]
for k in removed:
    ov.pop(k)
io.open(ov_f, 'w', encoding='utf-8').write(json.dumps(ov, ensure_ascii=False, indent=2))

print('归属人离职归并（规则同 cron Step 1）')
print('  归并：', dict(moved) or '（无命中）')
print('  已从 dept_overrides 移除：', removed or '（无）')
print('  归属人数 %d → %d' % (len(before), len({x['submitted_by'] for x in items})))
print('  剩余未在用户表的归属人：')
roles = {(u.get('name') or '').strip() for u in json.load(io.open(os.path.join(ROOT, '数据', 'user_roles.json'), encoding='utf-8'))}
left = Counter(x['submitted_by'] for x in items if x['submitted_by'] not in roles)
print('   ', dict(left) or '（全部在表 ✅）')
