# -*- coding: utf-8 -*-
import openpyxl, copy, sys, os, shutil, datetime, glob
sys.stdout.reconfigure(encoding='utf-8')
BLUE='FFBDD7EE'; NCOL=27; INST='한국지역난방공사'
xl=[g for g in glob.glob('*.xlsx') if '~$' not in g and 'backup' not in g.lower()][0]
mt0=os.path.getmtime(xl)
wb=openpyxl.load_workbook(xl); ws=wb.active; MAXR=ws.max_row
merged=list(ws.merged_cells.ranges)
def eff(r,c):
    v=ws.cell(r,c).value
    if v is not None: return v
    for rng in merged:
        if rng.min_row<=r<=rng.max_row and rng.min_col<=c<=rng.max_col:
            return ws.cell(rng.min_row,rng.min_col).value
    return None
def snap(r): return [copy.copy(ws.cell(r,c)._style) for c in range(1,NCOL+1)]
TPL=snap(160)  # 지역난방정보 페이지 행 스타일

A_ROW=('고객센터','고객서비스','고객서비스헌장','https://www.kdhc.co.kr/cyb/heat/cont/contentsView.do?menuCode=M020170&tabMenuCode=M020171&menuPreUrl=%2Fheat')
B_ROWS=[
 ('고객센터','고객마당','고객마당(열)','https://www.kdhc.co.kr/cyb/heat/main.do'),
 ('고객센터','고객마당','고객마당(전기)','https://www.kdhc.co.kr/cyb/elect/main.do'),
 ('고객센터','고객상담','상담FAQ','https://www.kdhc.co.kr/cyb/heat/board/faqListForm.do?menuCode=M020281&tabMenuCode=&menuPreUrl=%2Fheat'),
 ('고객센터','고객상담','상담하기','https://www.kdhc.co.kr/cyb/heat/board/consulListForm.do?menuCode=M020282&tabMenuCode=&menuPreUrl=%2Fheat&hpageCvapGrpCd=A012015'),
 ('고객센터','고객상담','고객제안','https://www.kdhc.co.kr/cyb/heat/board/consulWriteForm.do?menuCode=M020177&tabMenuCode=&menuPreUrl=%2Fheat&hpageCvapGrpCd=A012016&cvapSctgCd=C05001'),
 ('고객센터','RPS관리시스템',None,'https://rps.kdhc.co.kr/'),
 ('고객센터','고객신고센터','불편신고','https://www.kdhc.co.kr/cyb/heat/board/consulWriteForm.do?menuCode=M020178&tabMenuCode=&menuPreUrl=%2Fheat&hpageCvapGrpCd=A012020'),
 ('고객센터','고객신고센터','친절/불친절신고','https://www.kdhc.co.kr/cyb/heat/board/consulWriteForm.do?menuCode=M020180&tabMenuCode=&menuPreUrl=%2Fheat&hpageCvapGrpCd=A012017'),
 ('고객센터','민원 / 부패ㆍ공익신고','민원 / 부패ㆍ공익신고','https://www.kdhc.co.kr/cyb/heat/cont/contentsView.do?menuCode=M020312&tabMenuCode=&menuPreUrl=%2Fheat'),
 ('고객센터','민원 / 부패ㆍ공익신고','하도급부조리','https://www.kdhc.co.kr/cyb/heat/board/consulWriteForm.do?menuCode=M020294&tabMenuCode=&menuPreUrl=%2Fheat&hpageCvapGrpCd=A012019&cvapSctgCd=C02002'),
 ('고객센터','민원 / 부패ㆍ공익신고','예산낭비신고','https://www.kdhc.co.kr/cyb/heat/board/consulWriteForm.do?menuCode=M020293&tabMenuCode=&menuPreUrl=%2Fheat&hpageCvapGrpCd=A012019&cvapSctgCd=C02001'),
]

def base_record(r):
    vals={}
    for c in range(1,NCOL+1):
        vals[c]= eff(r,c) if 4<=c<=10 else ws.cell(r,c).value
    return {'vals':vals,'style':snap(r),'blue':set(),'new':False}

def site_record(D,E,F,url):
    vals={c:None for c in range(1,NCOL+1)}
    vals[3]=INST; vals[4]=D; vals[5]=E; vals[6]=F; vals[11]=url; vals[12]='사이트'
    return {'vals':vals,'style':[copy.copy(s) for s in TPL],'blue':set(range(2,18)),'new':True}

def is_content(r):
    return bool(any(eff(r,c) for c in range(4,11)) or ws.cell(r,11).value)

records=[]
for r in range(3,MAXR+1):
    if not is_content(r):   # skip trailing/empty rows entirely (no delete_rows needed)
        continue
    # insert B-rows BEFORE 개인정보 처리요구
    if eff(r,4)=='고객센터' and eff(r,5)=='개인정보 처리요구':
        for (D,E,F,u) in B_ROWS: records.append(site_record(D,E,F,u))
    records.append(base_record(r))
    # insert A-row AFTER 고객서비스선언
    if eff(r,4)=='고객센터' and eff(r,6)=='고객서비스선언':
        records.append(site_record(*A_ROW))

print('records',len(records),'(was',MAXR-2,') added',len(records)-(MAXR-2))

# rewrite
title=ws.title
hdr={}
for rr in (1,2):
    for c in range(1,NCOL+1):
        cell=ws.cell(rr,c); hdr[(rr,c)]=(cell.value,copy.copy(cell._style))
hdr_merges=[str(m) for m in merged if m.min_row<=2]
colw={k:v.width for k,v in ws.column_dimensions.items()}
del wb[title]; ns=wb.create_sheet(title)
for (rr,c),(v,st) in hdr.items():
    cc=ns.cell(rr,c); cc.value=v; cc._style=st
for m in hdr_merges: ns.merge_cells(m)
for col,w in colw.items():
    if w: ns.column_dimensions[col].width=w
from openpyxl.styles import PatternFill, Font, Alignment
bluefill=PatternFill(fill_type='solid',fgColor=BLUE,bgColor=BLUE)
linkfont=Font(name='맑은 고딕',size=10,color='0000FF',underline='single')
import datetime as _dt
ZDT=_dt.datetime(2026,6,21)
for i,rec in enumerate(records):
    R=3+i
    for c in range(1,NCOL+1):
        cell=ns.cell(R,c); cell._style=rec['style'][c-1]; cell.value=rec['vals'][c]
    ns.cell(R,2).value=i+1
    kv=rec['vals'][11]
    if kv and isinstance(kv,str) and kv.startswith('http'):
        kc=ns.cell(R,11); kc.hyperlink=kv; kc.font=linkfont
    # Y/Z/AA 검수완료 스탬프
    ns.cell(R,25).value='Y'; ns.cell(R,26).value=ZDT; ns.cell(R,26).number_format='yyyy-mm-dd'; ns.cell(R,27).value='프리랜서2'
    for c in (25,26,27): ns.cell(R,c).alignment=Alignment(horizontal='center',vertical='center')
    for c in rec['blue']: ns.cell(R,c).fill=bluefill
# re-merge D..J
D0=3; DN=3+len(records)-1
def val(R,c): return ns.cell(R,c).value
for c in range(4,11):
    R=D0
    while R<=DN:
        v=val(R,c)
        if v in (None,''): R+=1; continue
        r2=R
        while r2+1<=DN and val(r2+1,c)==v and all(val(r2+1,pc)==val(R,pc) for pc in range(4,c)):
            r2+=1
        if r2>R:
            for rr in range(R+1,r2+1): ns.cell(rr,c).value=None
            ns.merge_cells(start_row=R,start_column=c,end_row=r2,end_column=c)
        R=r2+1
ns.freeze_panes='A3'
os.makedirs('_backup',exist_ok=True)
shutil.copy2(xl,'_backup/_고객센터누락행추가전_'+datetime.datetime.fromtimestamp(mt0).strftime('%Y%m%d_%H%M%S')+'.xlsx')
if os.path.getmtime(xl)!=mt0: print('ABORT mtime'); sys.exit(1)
wb.save(xl)
print('SAVED rows',DN)
