# -*- coding: utf-8 -*-
import openpyxl, shutil
from copy import copy
from openpyxl.styles import PatternFill, Font, Alignment
from openpyxl.utils import get_column_letter as gl
XP='한국중부발전.xlsx'
BLUE=PatternFill('solid',fgColor='FFBDD7EE',bgColor='FFBDD7EE')
MAXCOL=27; HEADER_MERGES={'B1:R1','S1:W1','Y1:AA1'}
BB='https://www.komipo.co.kr'

# expansions: anchor_row -> list of new H-children (after self). self stays as anchor's H.
# each: (label, href, L, M, N)
EXP={
 183:{'self':'인권경영 보도자료','new':[
        ('월간 인권소식지','/esg/board/BRD_000117/boardMain.do?mnCd=ESG03030202','게시판',23,'어문,이미지'),
        ('전사 캠페인','/esg/board/BRD_000096/boardMain.do?mnCd=ESG03030203','게시판',39,'어문')]},
 184:{'self':'영상자료','new':[
        ('인권공모전','/esg/board/BRD_000115/boardMain.do?mnCd=ESG03030302','게시판',2,'어문,이미지'),
        ('인권경영 자료공유','/esg/board/BRD_000097/boardMain.do?mnCd=ESG03030303','게시판',29,'어문')]},
 208:{'self':'윤리경영 확산활동','new':[
        ('확산활동 및 자료실','/esg/board/BRD_000093/boardMain.do?mnCd=ESG04020302','게시판',16,'어문')]},
}
LEAFCOL=7  # G; children at 8(H)

wb=openpyxl.load_workbook(XP);ws=wb.active
for mr in list(ws.merged_cells.ranges):
    if str(mr) in HEADER_MERGES: continue
    top=ws.cell(mr.min_row,mr.min_col).value
    ws.unmerge_cells(str(mr))
    for rr in range(mr.min_row,mr.max_row+1):
        for cc in range(mr.min_col,mr.max_col+1):
            if ws.cell(rr,cc).value in (None,''): ws.cell(rr,cc).value=top

def cap(r):
    return {'vals':{c:ws.cell(r,c).value for c in range(1,MAXCOL+1)},
            'sty':{c:(copy(ws.cell(r,c).font),copy(ws.cell(r,c).fill),copy(ws.cell(r,c).border),
                      copy(ws.cell(r,c).alignment),ws.cell(r,c).number_format,copy(ws.cell(r,c).protection)) for c in range(1,MAXCOL+1)},
            'hl':ws.cell(r,11).hyperlink.target if ws.cell(r,11).hyperlink else None,'blue':set()}

final=[]
for r in range(3,ws.max_row+1):
    if all(ws.cell(r,c).value in (None,'') for c in range(2,MAXCOL+1)): continue
    rec=cap(r)
    if r in EXP:
        e=EXP[r]
        rec['vals'][LEAFCOL+1]=e['self']; rec['blue'].add(LEAFCOL+1)  # anchor: H=self label
        final.append(rec)
        for (lab,href,L,M,N) in e['new']:
            ch=cap(r)  # copy anchor styles/path(D..G same)
            for c in range(LEAFCOL+1,11): ch['vals'][c]=None
            ch['vals'][LEAFCOL+1]=lab
            url=BB+href
            ch['vals'][11]=url; ch['vals'][12]=L; ch['vals'][13]=M; ch['vals'][14]=N; ch['vals'][15]='미부착'
            for c in range(16,MAXCOL+1): ch['vals'][c]=None
            ch['vals'][2]=None  # new row B=None (user partial scheme)
            ch['vals'][3]='한국중부발전'
            ch['hl']=url; ch['blue']=set(range(2,16))
            final.append(ch)
    else:
        final.append(rec)

# write
START=3
for r in range(START,ws.max_row+1):
    for c in range(1,MAXCOL+1):
        ws.cell(r,c).value=None; ws.cell(r,c).hyperlink=None; ws.cell(r,c).fill=PatternFill()
for i,rec in enumerate(final):
    r=START+i
    for c in range(1,MAXCOL+1):
        cell=ws.cell(r,c); f,fl,bd,al,nf,pr=rec['sty'][c]
        cell.font=copy(f);cell.fill=copy(fl);cell.border=copy(bd);cell.alignment=copy(al);cell.number_format=nf;cell.protection=copy(pr)
        cell.value=rec['vals'][c]
END=START+len(final)-1
center=Alignment(horizontal='center',vertical='center',wrap_text=True)
def merge_runs(col):
    gcols=tuple(range(4,col))
    cur=ws.cell(START,col).value; grp=tuple(ws.cell(START,g).value for g in gcols); run=START; runs=[]
    for r in range(START+1,END+1):
        val=ws.cell(r,col).value; g=tuple(ws.cell(r,gg).value for gg in gcols)
        if val==cur and g==grp: continue
        if cur not in (None,'') and r-1>run: runs.append((run,r-1))
        cur,grp,run=val,g,r
    if cur not in (None,'') and END>run: runs.append((run,END))
    for s,e in runs:
        ws.merge_cells('%s%d:%s%d'%(gl(col),s,gl(col),e)); ws.cell(s,col).alignment=center
for col in (9,8,7,6,5,4): merge_runs(col)
for i,rec in enumerate(final):
    r=START+i; u=ws.cell(r,11).value
    if isinstance(u,str) and u.startswith(('http://','https://')) and rec['hl']:
        ws.cell(r,11).hyperlink=u; old=ws.cell(r,11).font
        ws.cell(r,11).font=Font(name=old.name or '맑은 고딕',size=old.size or 11,color='0000FF',underline='single')
    for c in rec['blue']: ws.cell(r,c).fill=copy(BLUE)
    ws.row_dimensions[r].height=15
shutil.copy(XP,XP.replace('.xlsx','_backup_게시판탭전개전.xlsx'))
wb.save(XP)
print('rows',len(final),'(was 222 data)')
