# -*- coding: utf-8 -*-
"""브라우저로 추출한 GNB 트리(_gnb\{num}.json)를 phase1.write_excel로 엑셀 기록.
사용: python _gnb_write.py {num} [{num} ...]
"""
import sys, io, os, json, importlib.util
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

SCRIPTS = r"D:\01.프로젝트\DB수집\_스크립트"
GNB_DIR = r"D:\01.프로젝트\DB수집\작업파일\공공기관2\_gnb"

# phase1 모듈 로드 (write_excel 재사용)
spec = importlib.util.spec_from_file_location("p1", os.path.join(SCRIPTS, "_공공기관2_phase1.py"))
p1 = importlib.util.module_from_spec(spec)
spec.loader.exec_module(p1)

COL = {1: 'D', 2: 'E', 3: 'F', 4: 'G', 5: 'H', 6: 'I', 7: 'J'}

def to_raw_rows(gnb):
    stack = {}
    raw = []
    for it in gnb:
        d = int(it['depth'])
        if d > 7:
            d = 7
        stack[d] = (it.get('label') or '').strip()
        for k in list(stack):
            if k > d:
                del stack[k]
        row = {}
        for i in range(1, d + 1):
            row[COL[i]] = stack.get(i, '')
        row['href'] = it.get('href') or ''
        raw.append(row)
    return raw

def main():
    nums = sys.argv[1:]
    for ns in nums:
        path = os.path.join(GNB_DIR, f"{ns}.json")
        if not os.path.exists(path):
            print(f"[{ns}] json 없음 — 스킵"); continue
        data = json.load(open(path, encoding='utf-8'))
        raw = to_raw_rows(data['gnb'])
        n = p1.write_excel(data['name'], int(data['num']), data['base'], raw)
        print(f"[{data['num']}.{data['name']}] write_excel → {n}행")

if __name__ == '__main__':
    main()
