import openpyxl
import sys
from openpyxl.styles import PatternFill, Font, Alignment, Border, Side
from openpyxl.utils import get_column_letter
from collections import defaultdict
sys.stdout.reconfigure(encoding='utf-8')

SRC = r'D:\01.프로젝트\DB수집\2주차\보건복지부_성평등가족부_외교부_20250506_프리랜서_20260528_검토완료.xlsx'
DST = r'D:\01.프로젝트\DB수집\2주차\보건복지부_성평등가족부_외교부_20250506_프리랜서_20260528_검토완료_누락추가.xlsx'

# (site, D, E, F, G, URL) — None means leave blank
MISSING = [
    # 보건복지부
    ('보건복지부', '민원', '민원이용안내', '민원신청', None, 'https://minwon.mohw.go.kr/'),
    ('보건복지부', '민원', '민원이용안내', '나의민원확인', None, 'https://minwon.mohw.go.kr/'),
    ('보건복지부', '민원', '부정청탁 및 금품 등 수수 신고', '신고내용확인(19.11.21 이전)', None, 'https://www.mohw.go.kr/menu.es?mid=a10215010000'),
    ('보건복지부', '민원', '부정청탁 및 금품 등 수수 신고', '신고내용확인(19.11.21 이후)', None, 'https://www.mohw.go.kr/menu.es?mid=a10215010000'),
    ('보건복지부', '참여', '제안신청', '제안신청', None, 'https://www.epeople.go.kr/'),
    ('보건복지부', '참여', '제안신청', '나의제안확인', None, 'https://www.epeople.go.kr/'),
    ('보건복지부', '참여', '장관과의 대화', '글작성', None, 'https://www.mohw.go.kr/board.es?mid=a10307010000&bid=0029'),
    ('보건복지부', '참여', '장관과의 대화', '답글확인', None, 'https://www.mohw.go.kr/board.es?mid=a10307010000&bid=0029'),
    ('보건복지부', '참여', '모범공직자추천', '글작성', None, 'https://www.mohw.go.kr/menu.es?mid=a10308010000'),
    ('보건복지부', '참여', '모범공직자추천', '답글확인', None, 'https://www.mohw.go.kr/menu.es?mid=a10308010000'),
    # 성평등가족부
    ('성평등가족부', '민원·참여', '민원신청', '나의 민원확인', None, 'https://www.mogef.go.kr/'),
    ('성평등가족부', '민원·참여', '국민제안', '국민제안', None, 'https://www.mogef.go.kr/'),
    ('성평등가족부', '민원·참여', '국민제안', '제안확인', None, 'https://www.mogef.go.kr/'),
    ('성평등가족부', '민원·참여', '사이버신고', '예산낭비신고', None, 'https://www.mogef.go.kr/'),
    ('성평등가족부', '유형별서비스', '교육정보', '교육자료실', None, 'https://www.mogef.go.kr/'),
    # 외교부
    ('외교부', '주요 외교활동', '장관 외교활동', None, None, 'https://www.mofa.go.kr/minister/brd/m_28687/list.do'),
    ('외교부', '국민참여', '대화의 장', '장관과의 대화', None, 'https://www.mofa.go.kr/www/brd/m_3852/list.do'),
    ('외교부', '국민참여', '대화의 장', '국민정책제안', None, 'https://www.epeople.go.kr/'),
    ('외교부', '국민참여', '민원접수', '일반민원신청', None, 'https://www.epeople.go.kr/'),
]

wb = openpyxl.load_workbook(SRC, data_only=False)
ws = wb['보건복지부']

# Find last seq per site
sites = {}
for row in range(4, ws.max_row+1):
    site = ws.cell(row=row, column=3).value
    if site:
        if site not in sites:
            sites[site] = {'first': row, 'last': row}
        else:
            sites[site]['last'] = row

last_seq = {}
for site, info in sites.items():
    max_seq = 0
    for row in range(info['first'], info['last']+1):
        v = ws.cell(row=row, column=2).value
        if isinstance(v, int) and v > max_seq:
            max_seq = v
    last_seq[site] = max_seq

YELLOW = PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid')
THIN = Side(border_style='thin', color='000000')
BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
CENTER = Alignment(horizontal='center', vertical='center', wrap_text=True)
LEFT = Alignment(horizontal='left', vertical='center', wrap_text=True)

# Group by site, in original site order
by_site = defaultdict(list)
for r in MISSING:
    by_site[r[0]].append(r)

# Append all missing at the bottom in order: 보건복지부 → 성평등가족부 → 외교부
site_order = ['보건복지부', '성평등가족부', '외교부']

next_row = ws.max_row + 1
for site in site_order:
    site_rows = by_site[site]
    if not site_rows: continue
    seq = last_seq[site]
    for s, d, e, f, g, url in site_rows:
        r = next_row
        seq += 1
        # Apply yellow + border to all cells B-AA
        for col in range(2, 28):
            c = ws.cell(row=r, column=col)
            c.fill = YELLOW
            c.border = BORDER
            c.alignment = CENTER
        # B: 순번
        ws.cell(row=r, column=2, value=seq)
        # C: 사이트명
        ws.cell(row=r, column=3, value=s)
        # D: 메뉴명
        ws.cell(row=r, column=4, value=d)
        # E: 카테고리(대)
        ws.cell(row=r, column=5, value=e)
        if f: ws.cell(row=r, column=6, value=f)
        if g: ws.cell(row=r, column=7, value=g)
        # K: URL with hyperlink
        if url:
            cell = ws.cell(row=r, column=11, value=url)
            cell.hyperlink = url
            cell.font = Font(color='0000FF', underline='single', name='맑은 고딕', size=11)
            cell.fill = YELLOW
            cell.alignment = LEFT
            cell.border = BORDER
        ws.row_dimensions[r].height = 15
        next_row += 1

wb.save(DST)
print(f'Saved: {DST}')

# Verify
wb2 = openpyxl.load_workbook(DST, data_only=False)
ws2 = wb2['보건복지부']
print(f'max_row: {ws2.max_row}')
yellow_rows = []
for r in range(1, ws2.max_row+1):
    fill = ws2.cell(row=r, column=2).fill
    if fill.fgColor and fill.fgColor.value == '00FFFF00':
        yellow_rows.append(r)
print(f'Yellow rows: {yellow_rows}')
for r in yellow_rows:
    b=ws2.cell(row=r,column=2).value; c=ws2.cell(row=r,column=3).value
    d=ws2.cell(row=r,column=4).value; e=ws2.cell(row=r,column=5).value
    f=ws2.cell(row=r,column=6).value; g=ws2.cell(row=r,column=7).value
    k=ws2.cell(row=r,column=11).value
    print(f'R{r}: B={b} C={c} D={d} E={e} F={f} G={g} K={(k or "")[:60]}')
