#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""① MCP 客户字段字典（找课题组线索）② 按采购额套用促销档位的草稿表。"""
import io
import json
from collections import Counter

ROOT = '/Users/liuxinyuan/Desktop/Hermes输出-工作类'
D = json.load(io.open(ROOT + '/销售分析/科研销售_按人与区域_20260820-20260930.json', encoding='utf-8'))

print('=== ① MCP 客户字段（mcp_customers.json）取值分布 ===')
items = json.load(io.open(ROOT + '/数据/mcp_customers.json', encoding='utf-8')).get('customers') or []
print('  条数', len(items))
for k in ['field_17186c', 'field_5ed7ab', 'field_6415cf', 'field_c3224b', 'field_c8e80d']:
    vals = []
    for it in items:
        v = it.get(k)
        if isinstance(v, dict):
            v = v.get('label') or v.get('name_cn') or ''
        vals.append(str(v or '').strip())
    c = Counter(v for v in vals if v)
    print('  %-14s 非空 %4d ｜ top: %s' % (k, sum(1 for v in vals if v), dict(c.most_common(5))))

# 字段名反查：用字段配置拿中文名（若本地缓存有）
for f in ('数据/customer_fields.json', '数据/mcp_customer_fields.json'):
    p = ROOT + '/' + f
    import os
    if os.path.exists(p):
        print('  字段说明文件:', f, json.dumps(json.load(io.open(p, encoding='utf-8')), ensure_ascii=False)[:300])

print('\n=== ② 按采购额套档位（草稿：口径待你确认）===')
TIERS = [(100000, 5000), (50000, 2500), (20000, 1000), (10000, 500), (5000, 250), (2000, 100), (1000, 50)]


def tier(amt_yuan):
    for th, gift in TIERS:
        if amt_yuan >= th:
            return th, gift
    return 0, 0


rows = []
for c in D['customers']:
    y = round(c['金额'] * 10000, 2)
    th, gift = tier(y)
    rows.append({'客户': c['客户'], '主跟销售': c['主跟销售'], '大区': c['大区'],
                 '订单数': c['订单数'], '金额元': y, '达标档位': th, '返礼品元': gift})
rows.sort(key=lambda r: -r['金额元'])

reach = Counter(r['达标档位'] for r in rows if r['达标档位'])
print('  客户 %d 家 ｜ 达档 %d 家 ｜ 未达 1000 元 %d 家'
      % (len(rows), sum(reach.values()), len(rows) - sum(reach.values())))
print('  档位分布:', {('%d元' % k): v for k, v in sorted(reach.items(), reverse=True)})
print('  礼品合计（元）: %d' % sum(r['返礼品元'] for r in rows))
print()
print('%-42s %-6s %10s %8s %8s' % ('客户', '主跟', '金额(元)', '档位', '礼品(元)'))
for r in rows:
    print('%-42s %-6s %10.2f %8s %8s' % (r['客户'][:40], r['主跟销售'], r['金额元'],
                                        ('%d' % r['达标档位']) if r['达标档位'] else '未达', r['返礼品元'] or '—'))
io.open(ROOT + '/销售分析/_draft_promo_tier_by_customer.json', 'w', encoding='utf-8').write(
    json.dumps({'caliber': '按促销期内采购额（价税合计，元）套用预存返利档位——口径待确认', 'rows': rows},
               ensure_ascii=False, indent=1))
print('\n草稿 → 销售分析/_draft_promo_tier_by_customer.json')
