# -*- coding: utf-8 -*-
import json, copy, shutil
import openpyxl
from openpyxl.styles import Font
FN='한국중부발전.xlsx'; NAME='한국중부발전'
tree=json.load(open('_komipo_tree.json',encoding='utf-8'))
Lmap={'CONTENT':'페이지','BOARD':'게시판','PROGRAM':'게시판','EXT':'사이트'}
shutil.copy(FN, FN.replace('.xlsx','_backup_재수집전.xlsx'))
wb=openpyxl.load_workbook(FN); ws=wb.active
styT={c: copy.copy(ws.cell(3,c)._style) for c in range(2,28)}
for m in list(ws.merged_cells.ranges):
    if m.min_row>=3: ws.unmerge_cells(str(m))
if ws.max_row>=3: ws.delete_rows(3, ws.max_row-2)
blue=Font(color='0000FF',underline='single')
r0=3; n=len(tree); last=r0+n-1
# 경로 배열(병합 판정용)
P={4:[],5:[],6:[],7:[]}
for t in tree:
    P[4].append(t['D']); P[5].append(t['E'] or ''); P[6].append(t['F'] or ''); P[7].append(t.get('G') or '')
# 쓰기
for i,t in enumerate(tree):
    r=r0+i
    for c in range(2,28): ws.cell(r,c)._style=copy.copy(styT[c])
    ws.cell(r,2).value=i+1; ws.cell(r,3).value=NAME
    for c in (4,5,6,7):
        v=P[c][i]; ws.cell(r,c).value=v if v else None
    url=t['url']; ws.cell(r,11).value=url; ws.cell(r,11).hyperlink=url; ws.cell(r,11).font=blue
    ws.cell(r,12).value=Lmap.get(t['type'],'페이지')
    ws.row_dimensions[r].height=15
# 병합 (배열 기준)
def prefix(i,c): return tuple(P[cc][i] for cc in range(4,c))
for c in (4,5,6,7):
    i=0
    while i<n:
        v=P[c][i]
        if not v: i+=1; continue
        j=i+1
        while j<n and P[c][j]==v and prefix(j,c)==prefix(i,c): j+=1
        if j-1>i:
            for k in range(i+1,j): ws.cell(r0+k,c).value=None
            ws.merge_cells(start_row=r0+i,start_column=c,end_row=r0+j-1,end_column=c)
        i=j
wb.save(FN)
print('Phase1 완료:',n,'행 (3~%d)'%last)
from collections import Counter
print('L:',dict(Counter(Lmap.get(t['type'],'페이지') for t in tree)))
