#!/usr/bin/env python3
"""月度数据校对：H1 存档 + H2 动态 vs KPI 目标
用法: python3 reconcile_monthly.py
输出: h1_archive/reconcile_2026-07.md
"""
import json, os, time
from datetime import date

ROOT = os.path.expanduser('~/Desktop/Hermes输出-工作类')
DATA = os.path.join(ROOT, '数据')
ARCHIVE = os.path.join(DATA, 'h1_archive')

today = date.today()
month_label = today.strftime('%Y-%m')

# 1. H1 存档
h1_all = os.path.join(ARCHIVE, 'h1_all.json')
h1_orders = []
if os.path.exists(h1_all):
    with open(h1_all) as f:
        h1_orders = json.load(f).get('orders', [])
h1_tax = sum(float(o.get('taxTotal', 0) or 0) for o in h1_orders)
h1_count = len(h1_orders)

# 2. H2 动态
ship_file = os.path.join(DATA, 'shipment_status.json')
h2_orders = []
if os.path.exists(ship_file):
    with open(ship_file) as f:
        h2_orders = json.load(f).get('orders', [])
h2_tax = sum(float(o.get('taxTotal', 0) or o.get('amount', 0) or 0) for o in h2_orders)
h2_count = len(h2_orders)

# 3. KPI 目标
kpi_file = os.path.join(DATA, 'kpi_dashboard.json')
kpi_target = 0
kpi_h1 = 0
if os.path.exists(kpi_file):
    with open(kpi_file) as f:
        kpi = json.load(f)
    kpi_target = kpi.get('total_target', 0)
    kpi_h1 = kpi.get('total_h1', 0)

# 4. KPI Progress (H2 month-to-date)
prog_file = os.path.join(DATA, 'kpi_progress.json')
prog_total = 0
if os.path.exists(prog_file):
    with open(prog_file) as f:
        prog = json.load(f)
    prog_total = prog.get('total', 0)

# 5. 计算
total_mcp_tax = h1_tax + h2_tax  # MCP 金额（可能偏低）
total_kpi = kpi_h1 + prog_total   # KPI 金额（权威）
h1_kpi_diff = kpi_h1 - h1_tax     # H1 KPI vs MCP 差异

# 6. 生成报告
lines = []
lines.append(f'# 📊 月度数据校对 · {month_label}')
fmt = today.strftime('%Y-%m-%d')
lines.append(f'> 生成时间: {fmt}')
lines.append('')
lines.append('## 一、H1 存档')
lines.append(f'- 订单数: {h1_count} 条')
lines.append(f'- MCP 税合计: {h1_tax/10000:.1f} 万')
lines.append(f'- KPI H1 实际: {kpi_h1/10000:.1f} 万')
lines.append(f'- 差异: {h1_kpi_diff/10000:.1f} 万 (KPI - MCP)')
lines.append(f'  > MCP 金额偏低原因：taxTotal 字段多为 0，实际金额以 KPI 为准')
lines.append('')
lines.append('## 二、H2 动态')
lines.append(f'- 订单数: {h2_count} 条')
lines.append(f'- MCP 税合计: {h2_tax/10000:.1f} 万')
lines.append(f'- KPI Progress: {prog_total/10000:.1f} 万')
lines.append('')
lines.append('## 三、全年累计')
lines.append(f'- KPI 年度目标: {kpi_target/10000:.1f} 万')
lines.append(f'- KPI 累计达成: {(kpi_h1 + prog_total)/10000:.1f} 万')
lines.append(f'- 达成率: {round((kpi_h1 + prog_total) / kpi_target * 100, 1)}%' if kpi_target else '- 达成率: 无目标')
lines.append('')
lines.append('## 四、需关注')
pct = round((kpi_h1 + prog_total) / kpi_target * 100, 1) if kpi_target else 0
if h1_kpi_diff > 100000:
    lines.append(f'- ⚠️ H1 MCP vs KPI 差异 {h1_kpi_diff/10000:.1f} 万，需确认 MCP taxTotal 填写率')
if pct < 50:
    lines.append(f'- ⚠️ 全年达成率 {pct}%，低于 50%，需关注')
lines.append('')

report = '\n'.join(lines)
out_path = os.path.join(ARCHIVE, f'reconcile_{month_label}.md')
with open(out_path, 'w', encoding='utf-8') as f:
    f.write(report)

print(report)
print(f'✅ 报告已保存: {out_path}')
