#!/usr/bin/env python3
"""Step 3/4 产物结构校验"""
import json, os
os.chdir(os.path.dirname(os.path.abspath(__file__)))

def check(fn, keys, listkey):
    p = fn
    if not os.path.exists(p):
        print('MISSING', fn); return
    d = json.load(open(p, encoding='utf-8'))
    items = d.get(listkey) or []
    print('%-28s %-8s len=%d  非空字段抽样:' % (fn, 'OK', len(items)), end=' ')
    if items:
        s = items[0]
        print({k: (str(s.get(k))[:18] if s.get(k) is not None else None) for k in keys})
    else:
        print('(空)')

check('activities_feishu.json', ['id','date','submitted_by','customer','channel','atype','dept_raw','type'], 'items')
check('daily_activities_mcp.json', ['name','start_time','field_b99055','field_5f20fc','field_76654e','field_5ed7ab','owner','work_item_id'], 'items')
check('mcp_orders_input.json', ['单据编号','客户名称','销售员','税合计','创建时间','work_item_id'], 'orders')

# 活动类型分布（Step3b 必须带活动类型）
d = json.load(open('daily_activities_mcp.json', encoding='utf-8'))
from collections import Counter
def lab(v):
    if isinstance(v, dict): return v.get('label','')
    if isinstance(v, list) and v: return ','.join(x.get('label','') if isinstance(x,dict) else str(x) for x in v)
    return str(v or '')
c = Counter(lab(x.get('field_76654e')) for x in d['items'])
print('daily_activities 活动类型分布:', dict(c))
print('daily_activities updated:', d.get('updated'), 'total:', d.get('total'))

o = json.load(open('mcp_orders_input.json', encoding='utf-8'))
print('orders top keys:', sorted(o.keys()))
oc = o.get('orders') or []
print('orders:', len(oc), '| 月份分布:', dict(Counter(str(x.get('创建时间',''))[:7] for x in oc)))
print('orders 金额合计:', round(sum(float(x.get('税合计') or 0) for x in oc), 2))
