# -*- coding: utf-8 -*-
r"""convert_all_parts.py — 전체 STEP 블럭화 일괄 실행기 [CEO 2026-07-20]
manifest.json의 STEP 원본(src)들을 convert_parts.py로 전부 블럭 변환한다.
이미 fab_models/parts/<모델>/ 가 있는 것은 건너뜀. 실패해도 다음 파일 계속.
결과는 fab_models/parts/_batch_log.txt 에 기록.
실행: python convert_all_parts.py
"""
import json, os, subprocess, sys, io

BASE = os.path.dirname(os.path.abspath(__file__))
PARTS = os.path.join(BASE, 'fab_models', 'parts')
LOG = os.path.join(PARTS, '_batch_log.txt')

def log(msg):
    print(msg, flush=True)
    with io.open(LOG, 'a', encoding='utf-8') as f:
        f.write(msg + '\n')

def main():
    man = json.load(io.open(os.path.join(BASE, 'fab_models', 'manifest.json'), encoding='utf-8'))
    items = man['items']
    done = skip = fail = 0
    for it in items:
        src = it.get('src') or ''
        if not src.lower().endswith(('.stp', '.step')):
            continue
        if not os.path.exists(src):
            log('[없음] ' + src); fail += 1; continue
        model = os.path.splitext(os.path.basename(src))[0].replace(' ', '_')
        out = os.path.join(PARTS, model)
        if os.path.isdir(out):
            skip += 1; continue
        log('[변환] ' + model)
        r = subprocess.run([sys.executable, os.path.join(BASE, 'convert_parts.py'),
                            src, model, '--depth', '2', '--max-parts', '120'],
                           capture_output=True, text=True, encoding='utf-8', errors='replace',
                           cwd=BASE, timeout=1800)
        if r.returncode == 0 and os.path.isdir(out):
            done += 1; log('  -> 성공')
        else:
            fail += 1
            log('  -> 실패: ' + (r.stderr or r.stdout or '')[-300:].replace('\n', ' | '))
    log('=== 완료: 성공 %d / 건너뜀 %d / 실패 %d ===' % (done, skip, fail))

if __name__ == '__main__':
    main()
