#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""把 MiniMax M1–M5 交付入库到工作区，并写验收记录。

源目录在 iCloud 上（dataless），先 brctl download 物化再逐字节复制，避免 Errno 11。
"""
import json
import os
import shutil
import subprocess
import time

SRC = ('/Users/liuxinyuan/Desktop/Minimax工作区/客户满意度2026/'
       '行业信息推送_M1-M5_2026-10-13')
DST = '/Users/liuxinyuan/Desktop/Hermes输出-工作类/数据/market_intel/minimax_2026-10-13'
FILES = ['m1_competitor_sources.json', 'm2_public_sources.json', 'm3_keyword_matrix.csv',
         'm4_event_rules.json', 'm5_collector_skeleton.py', '交付说明.md',
         'build_m1_m2.py', 'build_m3.py', 'build_m4.py', 'output/collected_events.jsonl']

os.makedirs(os.path.join(DST, 'output'), exist_ok=True)
ok, fail = [], []
for f in FILES:
    s, d = os.path.join(SRC, f), os.path.join(DST, f)
    try:
        with open(s, 'rb') as fh:
            data = fh.read()
        if not data:
            raise IOError('空内容（云上未物化）')
        with open(d, 'wb') as fh:
            fh.write(data)
        ok.append((f, len(data)))
    except Exception as e:
        subprocess.run(['brctl', 'download', s], capture_output=True)
        time.sleep(3)
        try:
            with open(s, 'rb') as fh:
                data = fh.read()
            with open(d, 'wb') as fh:
                fh.write(data)
            ok.append((f, len(data)))
        except Exception as e2:
            fail.append((f, str(e2)[:60]))

print('=== 入库结果 ===')
for f, n in ok:
    print('  ✅ %-34s %8d 字节' % (f, n))
for f, e in fail:
    print('  ❌ %-34s %s' % (f, e))

# 校验 JSON 可解析
print()
for f in ('m1_competitor_sources.json', 'm2_public_sources.json', 'm4_event_rules.json'):
    p = os.path.join(DST, f)
    try:
        d = json.load(open(p, encoding='utf-8'))
        print('  JSON 可解析: %-30s 顶层键 %s' % (f, list(d.keys())[:5] if isinstance(d, dict) else 'list'))
    except Exception as e:
        print('  JSON 异常: %s → %s' % (f, str(e)[:60]))
print('\n→ 入库目录:', DST)
