# -*- coding: utf-8 -*-
"""주택금융: 현재 시트→depth 트리 읽기 → 정보목록 3보드에 분류 카테고리 노드 삽입
→ _gnb\5.json 저장(이후 _gnb_write 5 + phase234로 재구성). 구조 보존+카테고리 추가."""
import sys, io, os, glob, json, re
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
import openpyxl

BASE = r"D:\01.프로젝트\DB수집\작업파일\공공기관2"
fp = [x for x in glob.glob(os.path.join(BASE, "5.*", "*.xlsx")) if "_backup" not in x and "~$" not in x][0]
COLS = list(range(4, 11))  # D..J
ws = openpyxl.load_workbook(fp).active

# 마지막 데이터행
endr = 2
for r in range(3, ws.max_row+1):
    if ws.cell(r,2).value is not None or any(ws.cell(r,c).value for c in COLS) or ws.cell(r,11).value:
        endr = r

# 시트 → 노드(depth,label,href) : diff기반(레벨 바뀌면 노드 emit, 리프만 href)
last = {c: None for c in COLS}
prev = {c: None for c in COLS}
nodes = []
for r in range(3, endr+1):
    for c in COLS:
        v = ws.cell(r,c).value
        if v not in (None,''):
            last[c] = v
            for cc in COLS:
                if cc > c: last[cc] = None
    eff = {c: last[c] for c in COLS}
    leafcols = [c for c in COLS if eff[c] not in (None,'')]
    if not leafcols:
        continue
    leafcol = max(leafcols)
    href = ws.cell(r,11).value or ''
    # prev와 비교해 처음 달라지는 깊이부터 leaf까지 노드 emit
    diff_from = None
    for c in COLS:
        if c > leafcol: break
        if eff[c] != prev.get(c):
            diff_from = c; break
    if diff_from is None:
        diff_from = leafcol  # 동일하면 leaf만(중복 방지용)
    for c in range(diff_from, leafcol+1):
        if eff[c] in (None,''): continue
        nodes.append({'depth': c-3, 'label': eff[c], 'href': href if c==leafcol else ''})
    prev = dict(eff)

print("원본 노드", len(nodes))

# 카테고리 데이터
CATS = {
    "sub06_04_01": ([("감사","24"),("윤리","25"),("기획","26"),("재정","27"),("법무","28"),("노무","29"),
                     ("인사","30"),("총무","31"),("회계","32"),("정보화","33"),("홍보","34"),("대외","35")], "표준정보목록"),
    "sub06_04_02": ([("주택구입","36"),("주택보증","37"),("주택연금","38"),("유동화증권","39"),("신용회복","40"),("재무","41"),("기타","42")], "고유정보목록"),
    "sub06_04_03": ([("감사","24"),("윤리","25"),("기획","26"),("재정","27"),("법무","28"),("노무","29"),
                     ("인사","30"),("총무","31"),("회계","32"),("정보화","33"),("홍보","34"),("대외","35")], "즐겨찾는목록"),
}

def board_key(href):
    m = re.search(r'(sub06_04_0[123])', href or '')
    return m.group(1) if m else None

# 노드 순회하며 해당 보드 leaf 노드 뒤에 카테고리(depth+1) 삽입
new = []
for nd in nodes:
    new.append(nd)
    bk = board_key(nd['href'])
    if bk in CATS and 'srCategoryId' not in nd['href']:
        cats, lbl = CATS[bk]
        # 라벨도 일치해야(자주찾는정보 r144 같은 동일URL 중복행엔 안 넣음)
        if nd['label'] == lbl:
            base = nd['href'].split('?')[0]
            for nm, cid in cats:
                new.append({'depth': nd['depth']+1, 'label': nm, 'href': f"{base}?mode=list&srCategoryId={cid}"})
            print(f"  {lbl}(d{nd['depth']}) +{len(cats)} 카테고리")

print("최종 노드", len(new))
out = {'num':5, 'name':'한국주택금융공사', 'base':'https://www.hf.go.kr', 'gnb': new}
json.dump(out, open(os.path.join(BASE,'_gnb','5.json'),'w',encoding='utf-8'), ensure_ascii=False, indent=1)
print("saved _gnb/5.json")
