# -*- coding: utf-8 -*-
"""_gnb/{num}.json → {num}.{name}/{name}.xlsx (Phase1 트리, p1.write_excel 재사용·OUTDIR=공공기관3)
사용: python _writetree.py {num} [num ...]"""
import sys, io, os, json, re, importlib.util
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

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

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)
p1.OUTDIR = OUT  # 출력 경로 override

COL = {1:'D',2:'E',3:'F',4:'G',5:'H',6:'I',7:'J'}
CLEAN = re.compile(r'(열기|닫기|펼치기)\s*$')

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

def main():
    for ns in sys.argv[1:]:
        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'))
        if not data.get('gnb'):
            print(f"[{ns}.{data.get('name')}] gnb 비어있음 — 스킵"); continue
        raw=to_raw(data['gnb'])
        n=p1.write_excel(data['name'], int(data['num']), data['base'], raw)
        print(f"[{data['num']}.{data['name']}] → {n}행")

if __name__=='__main__':
    main()
