#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""入库前基线快照：现用 ERP 文件 + 权威口径月度汇总（用于更新后比对差异）
aggregate(fp) → (monthly_total, monthly_person, monthly_dept, source)
每月字典结构：monthly_person[月][人名]、monthly_dept[月][部门]
"""
import os
import sys
import json
import datetime

ROOT = os.path.expanduser('~/Desktop/Hermes输出-工作类')
sys.path.insert(0, os.path.join(ROOT, '脚本'))
import erp_sales_core as core  # noqa: E402

fp = core.find_latest_erp()
mt, mp, md, src = core.aggregate(fp)

print('=' * 76)
print('现用 ERP 文件:', src)
print('文件路径    :', fp)
print('文件时间    :', datetime.datetime.fromtimestamp(os.path.getmtime(fp)).strftime('%Y-%m-%d %H:%M'))
print('文件行数    :', len(__import__('pandas').read_excel(fp, dtype=str)))
print('=' * 76)

W = 1e4
months = sorted(mt.keys())
print()
print('--- 月度总额（万元）---')
h1 = 0.0
for m in months:
    v = mt[m] / W
    if m <= '2026-06':
        h1 += v
    print('   %s   %10.1f 万' % (m, v))
print('   H1(1-6月) %10.1f 万' % h1)
print('   7月后合计  %10.1f 万' % (sum(mt[m] for m in months if m > '2026-06') / W))
print('   全年累计   %10.1f 万' % (sum(mt.values()) / W))

print()
print('--- 部门 × 月（万元）---')
depts = sorted({d for m in md for d in md[m]})
hdr = '   %-16s' % '部门' + ''.join('%9s' % m[5:] + '月' for m in months) + '%10s' % '合计'
print(hdr)
for d in depts:
    row = '   %-16s' % d[:16]
    tot = 0.0
    for m in months:
        v = md[m].get(d, 0) / W
        tot += v
        row += '%10.1f' % v
    print(row + '%10.1f' % tot)

print()
print('--- 个人 × 月（万元，仅 7 月起，前 30 人）---')
pm = sorted({p for m in mp for p in mp[m]},
            key=lambda p: -sum(mp[m].get(p, 0) for m in months))
print('   %-10s' % '姓名' + ''.join('%10s' % (m[5:] + '月') for m in months if m > '2026-06') + '%10s' % '7月后')
for p in pm[:30]:
    row = '   %-10s' % p[:10]
    tot = 0.0
    for m in months:
        if m <= '2026-06':
            continue
        v = mp[m].get(p, 0) / W
        tot += v
        row += '%10.1f' % v
    print(row + '%10.1f' % tot)

snap = {
    'captured_at': datetime.datetime.now().strftime('%Y-%m-%d %H:%M'),
    'source_file': src,
    'rows': len(__import__('pandas').read_excel(fp, dtype=str)),
    'monthly_total': {m: round(v, 2) for m, v in mt.items()},
    'monthly_dept': md,
    'monthly_person': mp,
}
out = os.path.join(ROOT, '数据/_erp_baseline_snapshot.json')
json.dump(snap, open(out, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
print()
print('✅ 基线快照已存:', out)
