#!/usr/bin/env python3
"""合并 14 个前端数据 JSON → 单一 workbench_data.json
用法: python3 merge_workbench_data.py
输出: ../数据/workbench_data.json
"""
import json, os, time

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA = os.path.join(ROOT, '数据')
OUTPUT = os.path.join(DATA, 'workbench_data.json')

FILES = {
    'customers':       'pricing/_key_customers.json',
    'personnel':       'pricing/_personnel.json',
    'kpiDashboard':    'kpi_dashboard.json',
    'kpiProgress':     'kpi_progress.json',
    'h1Monthly':       'h1_monthly.json',
    'myKpis':          'my_kpis.json',
    'complaints':      'mcp_complaints.json',
    'threeYearMonthly':'three_year_monthly.json',
    'h2Targets':       'h2_monthly_targets.json',
    'oppSandbox':      'opportunity_sandbox.json',
    'shipments':       'shipment_status.json',
    'mcpCustomers':    'mcp_customers.json',
    'customerContacts':'customer_contacts.json',
    'myActivities':    'my_activities.json',
}

result = {'_merged_at': time.strftime('%Y-%m-%d %H:%M:%S'), '_version': 2}
missing = []

for key, relpath in FILES.items():
    path = os.path.join(DATA, relpath)
    if os.path.exists(path):
        try:
            with open(path, encoding='utf-8') as f:
                result[key] = json.load(f)
        except Exception as e:
            print(f'  ⚠️ {key}: 解析失败 ({e})')
            result[key] = {}
            missing.append(key)
    else:
        print(f'  ⚠️ {key}: 文件不存在 ({relpath})')
        result[key] = {}
        missing.append(key)

os.makedirs(os.path.dirname(OUTPUT), exist_ok=True)

# 注入 H1 存档数据到 shipments
h1_all = os.path.join(DATA, 'h1_archive', 'h1_all.json')
if os.path.exists(h1_all) and 'shipments' in result:
    try:
        with open(h1_all, encoding='utf-8') as f:
            h1 = json.load(f)
        h1_orders = h1.get('orders', [])
        h2_orders = result['shipments'].get('orders', [])
        # 合并：H1在前（旧），H2在后（新），H2的同单号覆盖H1
        seen = set(o.get('orderId','') for o in h1_orders)
        for o in h1_orders:
            if not o.get('shipment'):
                o['shipment'] = {'status': 'archived', 'statusLabel': 'H1 归档'}
        merged = h1_orders + [o for o in h2_orders if o.get('orderId','') not in seen]
        merged = sorted(merged, key=lambda o: o.get('createDate',''), reverse=True)
        result['shipments'] = dict(result['shipments'])
        result['shipments']['orders'] = merged
        result['shipments']['total'] = len(merged)
        result['shipments']['h1_count'] = len(h1_orders)
        result['shipments']['h2_count'] = len([o for o in h2_orders if o.get('orderId','') not in seen])
        print(f'  H1 注入: {len(h1_orders)}条 + H2 {len(h2_orders)}条 = {len(merged)}条')
    except Exception as e:
        print(f'  ⚠️ H1 注入失败: {e}')

with open(OUTPUT, 'w', encoding='utf-8') as f:
    json.dump(result, f, ensure_ascii=False)

total_size = os.path.getsize(OUTPUT)
print(f'✅ {OUTPUT} ({total_size/1024/1024:.1f}MB, {len(FILES)} keys' + (f', {len(missing)} missing' if missing else '') + ')')
if missing:
    print(f'   缺失: {missing}')
