#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""增量 ERP 文件结构核验（合并前）"""
import pandas as pd
import os
import sys

sys.path.insert(0, os.path.expanduser('~/Desktop/Hermes输出-工作类/脚本'))
import erp_sales_core as core

import os as _os
NEW = _os.environ.get('ERP_INCREMENT') or ''
assert NEW and _os.path.exists(NEW), '请设置 ERP_INCREMENT 指向增量文件'
OLD_FP = core.find_latest_erp()

print('=' * 78)
print('【增量文件】', os.path.basename(NEW))
print('=' * 78)
new = pd.read_excel(NEW, dtype=str)
print('行数:', len(new), '｜ 列数:', len(new.columns))
print('列头:')
for i, c in enumerate(new.columns):
    print('   %2d %s' % (i, c))

d = new['合同日期'].apply(core.ser2date) if '合同日期' in new.columns else pd.Series(dtype=str)
print()
print('合同日期 min/max:', d.min(), '→', d.max())
print('空/异常日期行数:', sum(1 for x in d if not (isinstance(x, str) and len(x) == 10 and x[4] == '-')))
vc = d.value_counts().sort_index()
print('按日分布:')
for k, v in vc.items():
    print('   %s  %5d 行' % (k, v))

print()
print('单据类型分布:')
print(new['单据类型'].value_counts().to_string() if '单据类型' in new.columns else '（无该列）')
if '单据状态' in new.columns:
    print('单据状态分布:')
    print(new['单据状态'].value_counts().to_string())

print()
print('=' * 78)
print('【现用全年文件】', os.path.basename(OLD_FP))
print('=' * 78)
old = pd.read_excel(OLD_FP, dtype=str)
print('行数:', len(old), '｜ 列数:', len(old.columns))
do = old['合同日期'].apply(core.ser2date)
print('合同日期 min/max:', do.min(), '→', do.max())

print()
same = list(old.columns) == list(new.columns)
print('★ 列结构一致:', same)
if not same:
    print('  仅旧文件有:', [c for c in old.columns if c not in new.columns])
    print('  仅新文件有:', [c for c in new.columns if c not in old.columns])
print('★ 重叠区间行数（旧文件中 >= 新文件 min 日期的行）:',
      int((do >= d.min()).sum()))
