# -*- coding: utf-8 -*-
"""OECD보고서(F) 하위탭 3행(G) 삽입 + 22행+ O/P/Q 정정 + B 재부번(1~21 보존·스타일 보존)."""
import openpyxl, shutil, copy as _copy
from openpyxl.styles import PatternFill, Font
BLUE=PatternFill('solid',fgColor='FFBDD7EE',bgColor='FFBDD7EE')
SRC='한국조세재정연구원.xlsx'
shutil.copy(SRC,'한국조세재정연구원_backup_OECD탭전개전.xlsx')
wb=openpyxl.load_workbook(SRC); ws=wb.active
maxr=ws.max_row
def data_row(r): return any(ws.cell(r,c).value not in (None,'') for c in range(2,18))

# eff D~F (filled down)
eff={}
for r in range(3,maxr+1):
    for c in range(4,7): eff[(r,c)]=ws.cell(r,c).value
for m in list(ws.merged_cells.ranges):
    if m.min_row>=3 and 4<=m.min_col<=6:
        top=ws.cell(m.min_row,m.min_col).value
        for rr in range(m.min_row,m.max_row+1): eff[(rr,m.min_col)]=top

# snapshot records with per-cell style (cols 2..17)
rows=[]
for r in range(3,maxr+1):
    if not data_row(r): continue
    sty={c:(_copy.copy(ws.cell(r,c).font),_copy.copy(ws.cell(r,c).fill),
            _copy.copy(ws.cell(r,c).border),_copy.copy(ws.cell(r,c).alignment)) for c in range(2,18)}
    rec={'vals':{c:ws.cell(r,c).value for c in range(2,18)},
         'D':eff.get((r,4)),'E':eff.get((r,5)),'F':eff.get((r,6)),
         'hl':ws.cell(r,11).hyperlink.target if ws.cell(r,11).hyperlink else None,
         'sty':sty,'h':ws.row_dimensions[r].height}
    # overwrite D/E/F with eff so every row carries them
    rec['vals'][4]=rec['D']; rec['vals'][5]=rec['E']; rec['vals'][6]=rec['F']
    rows.append(rec)
print('원본 데이터행',len(rows))
tmpl=rows[0]['sty']  # style template for new rows (from row3)

# insert OECD children
OECDc=[('중간보고서','https://www.kipf.re.kr/kor/data/OECDReport/beDataRoom/list.do?kind=OECD1',14),
       ('최종보고서','https://www.kipf.re.kr/kor/data/OECDReport/beDataRoom/list.do?kind=OECD2',16),
       ('후속보고서','https://www.kipf.re.kr/kor/data/OECDReport/beDataRoom/list.do?kind=OECD3',49)]
new=[]
for rec in rows:
    new.append(rec)
    if rec['F']=='OECD보고서' and (rec['vals'][7] in (None,'')):
        for lab,url,m in OECDc:
            cv={2:None,3:'한국조세재정연구원',4:rec['D'],5:rec['E'],6:'OECD보고서',7:lab,8:None,9:None,10:None,
                11:url,12:'게시판',13:m,14:'어문',15:'미부착',16:None,17:None}
            new.append({'vals':cv,'D':rec['D'],'E':rec['E'],'F':'OECD보고서','hl':url,
                        'sty':{c:(_copy.copy(t[0]),_copy.copy(t[1]),_copy.copy(t[2]),_copy.copy(t[3])) for c,t in tmpl.items()},
                        'h':rec['h'],'NEW':True})
print('확장후',len(new))

# O/P/Q 4유형 보정
def is4(u):
    u=str(u or '')
    return ('RecommendationsReport/kiPublish/list.do' in u) or ('Center_CaReport/kiPublish' in u) or ('Announce/kiAnnounce/list.do' in u)
fixed=[]
for rec in new:
    if rec['vals'].get(12)=='게시판' and is4(rec['vals'].get(11)):
        ch=(rec['vals'].get(15)!='4유형')
        rec['vals'][15]='4유형'; rec['vals'][16]='게시물'; rec['vals'][17]='Y'
        if ch: rec['_opq']=True
        fixed.append(rec['vals'].get(6) or rec['vals'].get(5))
print('OPQ 4유형:',fixed)

# wipe & rewrite
for m in list(ws.merged_cells.ranges):
    if m.min_row>=3: ws.unmerge_cells(str(m))
for r in range(3,maxr+8):
    for c in range(2,28):
        cc=ws.cell(r,c); cc.value=None; cc.hyperlink=None
        cc.fill=PatternFill(); cc.font=Font()
r=3
for i,rec in enumerate(new,1):
    for c in range(2,18):
        cell=ws.cell(r,c); cell.value=rec['vals'].get(c)
        f,fi,bo,al=rec['sty'][c]
        cell.font=f; cell.fill=fi; cell.border=bo; cell.alignment=al
    ws.cell(r,2).value=i  # B 재부번
    if rec.get('hl'):
        ws.cell(r,11).hyperlink=rec['hl']; ws.cell(r,11).font=Font(color='0000FF',underline='single')
    if rec.get('NEW'):
        for c in range(2,18): ws.cell(r,c).fill=BLUE
    elif rec.get('_opq'):
        for c in (15,16,17): ws.cell(r,c).fill=BLUE
    if rec.get('h'): ws.row_dimensions[r].height=rec['h']
    r+=1
last=r-1

# remerge D,E,F by value runs
for col in (4,5,6):
    rr=3
    while rr<=last:
        v=ws.cell(rr,col).value
        if v in (None,''): rr+=1; continue
        r2=rr
        while r2+1<=last and ws.cell(r2+1,col).value==v: r2+=1
        if r2>rr:
            for x in range(rr+1,r2+1): ws.cell(x,col).value=None
            ws.merge_cells(start_row=rr,start_column=col,end_row=r2,end_column=col)
        rr=r2+1
wb.save(SRC)
print(f'저장 완료. 행수={last-2} (rows 3..{last})')
