# -*- coding: utf-8 -*-
"""개인정보처리방침(F) 하위 con탭 4개(페이지) 국소삽입."""
import sys, io, os, glob
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
from copy import copy
import openpyxl
from openpyxl.styles import Font

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)); HEADER=['B1:R1','S1:W1','Y1:AA1']
CHILDREN=[("알기 쉬운 개인정보처리방침","sub05_09_01_05"),("목적 외 이용 및 제3자 제공","sub05_09_01_02"),
          ("개인(신용)정보처리 위탁현황","sub05_09_01_03"),("가명정보처리현황","sub05_09_01_04")]

mt0=os.path.getmtime(fp)
wb=openpyxl.load_workbook(fp); ws=wb.active
# 부모 찾기
pr=None
for r in range(3,ws.max_row+1):
    if str(ws.cell(r,11).value or '').endswith('sub05_09_01_01.do') or 'sub05_09_01_01' in str(ws.cell(r,11).value or ''):
        pr=r; break
if not pr: print("부모없음"); sys.exit(1)
childcol=7  # 개인정보처리방침은 F(6)이므로 자식 G(7)
print("부모 r",pr)
# 전체 unmerge
for m in [str(x) for x in ws.merged_cells.ranges]: ws.unmerge_cells(m)
# 삽입
ws.insert_rows(pr+1,len(CHILDREN))
for i,(nm,key) in enumerate(CHILDREN):
    rr=pr+1+i
    for c in range(2,28):
        s=ws.cell(pr,c)
        if s.has_style:
            d=ws.cell(rr,c); d.font=copy(s.font);d.fill=copy(s.fill);d.border=copy(s.border);d.alignment=copy(s.alignment);d.number_format=s.number_format
    ws.cell(rr,3).value=ws.cell(pr,3).value
    ws.cell(rr,childcol).value=nm
    ws.cell(rr,11).value=f"https://www.hf.go.kr/ko/sub05/{key}.do"
    ws.cell(rr,12).value='페이지'; ws.cell(rr,13).value=1; ws.cell(rr,14).value='어문'; ws.cell(rr,15).value='미부착'
# endr
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
# fill-down
last={c:None for c in COLS}
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
    for c in COLS:
        if ws.cell(r,c).value in (None,'') and last[c] not in (None,''): ws.cell(r,c).value=last[c]
# 재병합
def us(r1,r2,c): return all(ws.cell(r1,cc).value==ws.cell(r2,cc).value for cc in COLS if cc<c)
for c in sorted(COLS,reverse=True):
    r=3
    while r<=endr:
        v=ws.cell(r,c).value
        if v in (None,''): r+=1; continue
        r2=r
        while r2+1<=endr and ws.cell(r2+1,c).value==v and us(r,r2+1,c): r2+=1
        if r2>r: ws.merge_cells(start_row=r,start_column=c,end_row=r2,end_column=c)
        r=r2+1
for m in HEADER: ws.merge_cells(m)
# B+K
bn=0
for r in range(3,endr+1):
    if any(ws.cell(r,c).value for c in COLS) or ws.cell(r,11).value: bn+=1; ws.cell(r,2).value=bn
    k=ws.cell(r,11); u=k.value
    if u and isinstance(u,str) and u.startswith('http'):
        k.hyperlink=u; o=k.font; k.font=Font(name=o.name or '맑은 고딕',size=o.size or 11,color='0000FF',underline='single')
if abs(os.path.getmtime(fp)-mt0)>0.5: print("ABORT mtime"); sys.exit(1)
wb.save(fp); print("저장완료 데이터행",bn)
