#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""把 transfer_progress_20261031.json 应用到 product_master.json。

规则：
- 只有 master_match == exact 的货号，才写入 SKU 级 transfer 字段；
- 转产成功的 exact 货号才把 produced 置为“是”；
- 不向 product_master 新造未知 SKU（缺主数据的货号保留在顶层 transfer_progress.items，供 AI/页面回退查询）；
- 每次运行先备份，可重复执行。
"""
import json, pathlib, shutil
from datetime import datetime

ROOT = pathlib.Path('/Users/liuxinyuan/Desktop/Hermes输出-工作类')
PM = ROOT / '数据/product_master.json'
TP = ROOT / '数据/transfer_progress_20261031.json'

def main():
    tp = json.loads(TP.read_text(encoding='utf-8'))
    pm = json.loads(PM.read_text(encoding='utf-8'))
    stamp = datetime.now().strftime('%Y%m%d-%H%M%S')
    bak = PM.with_name('product_master.json.bak-transfer-%s' % stamp)
    shutil.copy2(PM, bak)

    items = tp.get('items') or []
    by_code = {x['code']: x for x in items}
    src = tp.get('source') or {}
    updated = tp.get('generated') or ''
    applied, success_flipped, not_exact = [], [], []
    for e in pm.get('skus') or []:
        c = e.get('sku')
        it = by_code.get(c)
        if not it:
            continue
        if it.get('master_match') != 'exact':
            not_exact.append(c)
            continue
        e['transfer'] = {
            'code': c,
            'status_group': it.get('status_group'),
            'status_label': it.get('status_label'),
            'progress': it.get('progress'),
            'next_plan': it.get('next_plan') or '',
            'line_note': it.get('line_note') or '',
            'issue_note': it.get('issue_note') or '',
            'source_section': it.get('source_section') or '',
            'source': '刘贝欣邮件《回复：【会议纪要】产销协调会》%s' % (src.get('sent') or '2026-10-31'),
            'updated': updated,
        }
        applied.append(c)
        if it.get('status_group') == 'success' and e.get('produced') != '是':
            e['produced'] = '是'
            success_flipped.append(c)

    pm['transfer_progress'] = {
        'generated': updated,
        'source': src,
        'summary': tp.get('summary') or {},
        'items': items,
        'note': ('只有 master_match=exact 的货号写入 SKU 级 transfer；'
                 '主数据未收录的货号保留在 items 中，按 code 回退查询。'),
    }
    pm['transfer_progress_updated'] = updated
    PM.write_text(json.dumps(pm, ensure_ascii=False, indent=1), encoding='utf-8')
    print('backup:', bak)
    print('applied exact:', len(applied), applied)
    print('produced -> 是:', len(success_flipped), success_flipped)
    print('not exact (kept in top-level only):', len(not_exact), not_exact)
    print('top-level transfer items:', len(items))

if __name__ == '__main__':
    main()
