#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""数据包隔离审计：把包里出现的每个客户，追溯到它命中的客户清单关键词。

用途：证明「包里的数据都属于本人客户」，且每个客户的纳入理由可溯源。
用法：python3 verify_sales_data_pack.py 刘子研
"""
import collections
import importlib.util
import json
import os
import sys

ROOT = '/Users/liuxinyuan/Desktop/Hermes输出-工作类'
spec = importlib.util.spec_from_file_location('b', os.path.join(ROOT, '脚本/build_sales_data_pack.py'))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)


def main():
    person = sys.argv[1] if len(sys.argv) > 1 else '刘子研'
    attrib = json.load(open(m.ATTRIB, encoding='utf-8'))
    names = (attrib['salespeople'].get(person) or {}).get('customers', [])
    kws = m.keywords(names)
    d = os.path.join(ROOT, '团队共享/销售数据包', person)
    print('数据包：%s ｜ 客户清单 %d 家 ｜ 关键词 %d 个' % (d, len(names), len(kws)))
    print()
    ok = True
    for f, key in (('01_飞书活动.json', 'customer'), ('02_客诉.json', 'customer'),
                   ('03_订单明细.json', '客户'), ('05_客户特殊要求.json', 'customer')):
        o = json.load(open(os.path.join(d, f), encoding='utf-8'))
        custs = collections.Counter([i.get(key) for i in o['items'] if i.get(key)])
        print('── %s ｜ %s 条 ｜ %d 个客户' % (f, o.get('_条数'), len(custs)))
        for c in sorted(custs):
            hits = sorted([k for k in kws if k in str(c)], key=len, reverse=True)
            flag = '✅' if hits else '❌ 无来源！'
            if not hits:
                ok = False
            print('   %s %-44s ← %s' % (flag, str(c)[:44], hits[:2]))
        print()
    o = json.load(open(os.path.join(d, '04_成交价历史.json'), encoding='utf-8'))
    print('── 04_成交价历史.json ｜ %d 个客户' % o['_客户数'])
    for c in sorted(o['hist']):
        hits = sorted([k for k in kws if k in str(c)], key=len, reverse=True)
        if not hits:
            ok = False
        print('   %s %-44s ← %s' % ('✅' if hits else '❌ 无来源！', str(c)[:44], hits[:2]))
    print()
    print('审计结论：%s' % ('✅ 全部客户都能追溯到本人客户清单' if ok else '❌ 存在无来源客户，需修'))
    return 0 if ok else 1


if __name__ == '__main__':
    sys.exit(main())
