#!/usr/bin/env python3
"""
KPI 更新管道 v6 — 从 ERP 全年订单文件完整更新工作台销售额（H1 + H2）
口径：标准销售订单 + 已审核 + 非赠品 + 剔除宝锐系（erp_sales_core）
人员映射：黄明月/张立娅 → 刘子研；刘新元(代管23家客户) → 刘子研
更新文件：
  - kpi_dashboard.json  （H1 + H2 的 people/depts/totals）
  - three_year_monthly.json （2026年1-8月）
  - h1_monthly.json （H1 部门 actuals）
"""
import json, os, sys, importlib.util
from datetime import datetime

BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # 工作区根
DATA = os.path.join(BASE, '数据')
KPI_FILE = os.path.join(DATA, 'kpi_dashboard.json')

_spec = importlib.util.spec_from_file_location('erp_sales_core', os.path.join(BASE, '脚本', 'erp_sales_core.py'))
core = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(core)

H1_MONTHS = ['2026-01', '2026-02', '2026-03', '2026-04', '2026-05', '2026-06']
H2_MONTH_IDX = {'2026-07': 0, '2026-08': 1, '2026-09': 2, '2026-10': 3, '2026-11': 4, '2026-12': 5}

def _rate(actual, target):
    return round(actual / target * 100, 1) if target else 0

def update(monthly_total, monthly_person, monthly_dept, fname):
    with open(KPI_FILE, encoding='utf-8') as f:
        kpi = json.load(f)

    # ── H1：people / depts（仅当文件含 H1 月才更新，避免"仅当月"文件清空 H1）──
    has_h1 = any(m in monthly_total for m in H1_MONTHS)
    if has_h1:
        for person in kpi['people']:
            pname = person['name']
            person['h1_months'] = [round(monthly_person.get(m, {}).get(pname, 0), 2) for m in H1_MONTHS]
            person['h1_total'] = round(sum(person['h1_months']), 2)
            person['h1_rate'] = _rate(person['h1_total'], person.get('target', 0))
        for dept in kpi['depts']:
            dn = dept['dept']
            dept['h1_months'] = [round(monthly_dept.get(m, {}).get(dn, 0), 2) for m in H1_MONTHS]
            dept['h1_total'] = round(sum(dept['h1_months']), 2)
            dept['h1_rate'] = _rate(dept['h1_total'], dept.get('target', 0))

    # ── H2：people ──
    for person in kpi['people']:
        pname = person['name']
        if 'h2_actual_months' not in person or len(person['h2_actual_months']) < 6:
            person['h2_actual_months'] = [0] * 6
        for m, idx in H2_MONTH_IDX.items():
            if m in monthly_total:
                person['h2_actual_months'][idx] = round(monthly_person.get(m, {}).get(pname, 0), 2)
        person['h2_actual'] = round(sum(person['h2_actual_months']), 2)
        person['h2_remain'] = round(person.get('target', 0) - person['h1_total'] - person['h2_actual'], 2)

    # ── H2：depts ──
    for dept in kpi['depts']:
        dn = dept['dept']
        if 'h2_actual_months' not in dept or len(dept['h2_actual_months']) < 6:
            dept['h2_actual_months'] = [0] * 6
        for m, idx in H2_MONTH_IDX.items():
            if m in monthly_total:
                dept['h2_actual_months'][idx] = round(monthly_dept.get(m, {}).get(dn, 0), 2)
        dept['h2_actual'] = round(sum(dept['h2_actual_months']), 2)
        dept['h2_remain'] = round(dept.get('target', 0) - dept['h1_total'] - dept['h2_actual'], 2)

    # ── totals（从部门汇总反推，确保"仅当月"文件场景下不丢失历史月）──
    if has_h1:
        h1_total = round(sum(dept['h1_total'] for dept in kpi['depts']), 2)
        kpi['total_h1'] = h1_total
        kpi['total_h1_rate'] = _rate(h1_total, kpi.get('total_target', 0))
    else:
        h1_total = kpi.get('total_h1', 0)
    h2_total = round(sum(dept['h2_actual'] for dept in kpi['depts']), 2)
    kpi['total_h2_actual'] = h2_total
    kpi['total_h1_h2'] = round(h1_total + h2_total, 2)
    kpi['source'] = f'ERP销售订单导出({datetime.now().strftime("%Y%m%d")})'
    kpi['updated_at'] = datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
    kpi['period'] = f"2026年 (全年=ERP·累计{kpi['total_h1_h2']/1e4:.1f}万)"

    with open(KPI_FILE, 'w', encoding='utf-8') as f:
        json.dump(kpi, f, ensure_ascii=False, indent=2)

    # ── 同步 three_year_monthly 2026年1-8月 ──
    tym_file = os.path.join(DATA, 'three_year_monthly.json')
    if os.path.exists(tym_file):
        with open(tym_file, encoding='utf-8') as f:
            tym = json.load(f)
        for m in list(H1_MONTHS) + list(H2_MONTH_IDX):
            if m in monthly_total:
                tym['2026'][str(int(m[5:7]))] = round(monthly_total[m], 2)
        tym.setdefault('meta', {})['generated'] = datetime.now().strftime('%Y-%m-%d')
        tym['meta']['source_2026'] = f'ERP销售订单导出({datetime.now().strftime("%Y%m%d")}) 标准+已审核+非赠品+非宝锐系'
        with open(tym_file, 'w', encoding='utf-8') as f:
            json.dump(tym, f, ensure_ascii=False, indent=2)

    # ── 同步 h1_monthly H1 actuals（仅当文件含 H1 月）──
    h1m_file = os.path.join(DATA, 'h1_monthly.json')
    if has_h1 and os.path.exists(h1m_file):
        with open(h1m_file, encoding='utf-8') as f:
            h1m = json.load(f)
        h1_actuals = [round(monthly_total.get(m, 0), 2) for m in H1_MONTHS]
        if 'total' in h1m:
            h1m['total']['actuals'] = h1_actuals
            h1m['total']['h1_actual'] = round(sum(h1_actuals), 2)
        for dn, dv in h1m.get('depts', {}).items():
            dv['actuals'] = [round(monthly_dept.get(m, {}).get(dn, 0), 2) for m in H1_MONTHS]
            dv['q1_a'] = round(sum(dv['actuals'][:3]), 2)
            dv['q2_a'] = round(sum(dv['actuals'][3:]), 2)
            dv['rates'] = [_rate(a, t) for a, t in zip(dv['actuals'], dv.get('targets', [0]*6))]
        with open(h1m_file, 'w', encoding='utf-8') as f:
            json.dump(h1m, f, ensure_ascii=False, indent=2)

    return kpi, h1_total, h2_total

def main():
    fp = core.find_latest_erp()
    if not fp:
        print('❌ 无 ERP 文件')
        sys.exit(1)
    monthly_total, monthly_person, monthly_dept, fname = core.aggregate(fp)
    kpi, h1_total, h2_total = update(monthly_total, monthly_person, monthly_dept, fname)
    print(f'✅ H1={h1_total/1e4:.1f}万 H2={h2_total/1e4:.1f}万 累计={kpi["total_h1_h2"]/1e4:.1f}万 (from {fname})')

if __name__ == '__main__':
    main()
