#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""H1 归档修复（P1 金额 + P2 轨迹）

P1：金额改用 ERP 价税合计（orders_detail_2026.json），MCP 原值存 mcpAmount
P2：H1 有运单号但无轨迹的单，走「月结归属查询」（不带手机号），失败再回落手机后4位
输出：数据/h1_archive/h1_all.json（原地，先备份）+ 数据/h1_archive/h1_summary.json 状态计数
"""
import json
import os
import re
import sys
import time
import unicodedata

ROOT = '/Users/liuxinyuan/Desktop/Hermes输出-工作类'
sys.path.insert(0, os.path.join(ROOT, '脚本'))
import shipment_pipeline as sp  # noqa: E402

H1 = os.path.join(ROOT, '数据', 'h1_archive', 'h1_all.json')
SUM = os.path.join(ROOT, '数据', 'h1_archive', 'h1_summary.json')
DET = os.path.join(ROOT, '数据', 'orders_detail_2026.json')
BAK = H1 + '.bak-%s' % time.strftime('%Y%m%d-%H%M%S')


def phone4(p):
    d = ''.join(c for c in unicodedata.normalize('NFKC', str(p or '')) if c.isdigit())
    if d.startswith('0086'):
        d = d[4:]
    elif len(d) == 13 and d.startswith('86'):
        d = d[2:]
    return d[-4:] if len(d) >= 4 else None


def main():
    only_amounts = '--amounts-only' in sys.argv
    data = json.load(open(H1, encoding='utf-8'))
    orders = data['orders']
    det = json.load(open(DET, encoding='utf-8'))['orders']

    # ---------- P1 金额 ----------
    n_amt = 0
    for o in orders:
        hit = det.get(str(o.get('orderId')))
        if not hit:
            continue
        total = float(hit.get('total') or 0)
        if total <= 0:
            continue
        old = o.get('taxTotal')
        if o.get('amountSource') != 'ERP':
            o['mcpAmount'] = old
        o['amount'] = o['taxTotal'] = round(total, 2)
        o['amountSource'] = 'ERP'
        o['erpLines'] = len(hit.get('lines') or [])
        n_amt += 1
    print('P1 金额改为 ERP：%d 单' % n_amt)

    # ---------- P2 轨迹 ----------
    targets = [o for o in orders if (o.get('trackingNo') or '').strip()
               and not ((o.get('shipment') or {}).get('routes'))]
    print('P2 待查轨迹：%d 单' % len(targets))
    if not only_amounts and targets:
        tok = sp.sf_get_token()
        ok = fail = 0
        for i, o in enumerate(targets, 1):
            tn = o['trackingNo'].strip()
            got = None
            try:
                r = sp.sf_query_routes([tn], tok, None)
                pr = sp.parse_routes(r) if isinstance(r, dict) and 'error' not in r else {}
                info = (pr or {}).get(tn)
                if info and info.get('routes'):
                    got, mode = info, 'owner'
                else:
                    p4 = phone4(o.get('phone'))
                    if p4:
                        r2 = sp.sf_query_routes([tn], tok, p4)
                        pr2 = sp.parse_routes(r2) if isinstance(r2, dict) and 'error' not in r2 else {}
                        i2 = (pr2 or {}).get(tn)
                        if i2 and i2.get('routes'):
                            got, mode = i2, 'phone'
            except Exception as e:
                print('  异常', tn, e)
            if got:
                got['queryMode'] = mode
                o['shipment'] = got
                ok += 1
            else:
                o['shipment'] = {'mailNo': tn, 'status': 'no_data', 'statusLabel': '暂无数据',
                                 'lastRoute': None, 'routes': [], 'reason': '查询无返回', 'routeCount': 0}
                fail += 1
            if i % 50 == 0:
                print('  进度 %d/%d 成功 %d 失败 %d' % (i, len(targets), ok, fail), flush=True)
                json.dump(data, open(H1 + '.tmp', 'w', encoding='utf-8'), ensure_ascii=False)
            time.sleep(0.05)
        print('P2 结果：成功 %d ｜ 无数据 %d' % (ok, fail))

    # ---------- 汇总 ----------
    from collections import Counter
    st = Counter((o.get('shipment') or {}).get('statusLabel') or '无物流' for o in orders)
    if os.path.exists(SUM):
        s = json.load(open(SUM, encoding='utf-8'))
        s['status'] = dict(st)
        s['updated_at'] = time.strftime('%Y-%m-%d %H:%M:%S')
        json.dump(s, open(SUM, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
    data['generated_at'] = time.strftime('%Y-%m-%d %H:%M:%S')
    json.dump(data, open(H1 + '.tmp', 'w', encoding='utf-8'), ensure_ascii=False)
    os.replace(H1 + '.tmp', H1)
    print('✅ 写入', H1, '｜状态分布', st.most_common(6))


if __name__ == '__main__':
    if not os.path.exists(BAK):
        import shutil
        shutil.copy2(H1, BAK)
        print('备份', BAK)
    main()
