# -*- coding: utf-8 -*-
"""서산 관광지(bbsNo=617) bbs_category_list 5카테고리를 H열 게시판 하위행으로 삽입.
관광지=전체(M11) 유지, 카테고리: 아라메길3·해미읍성1·버드랜드1·삼길포항1·기타5.
insert_rows 후 병합 재매핑 + 하이퍼링크 전체 재구성(insert버그 대응).
사용: python -X utf8 _서산_관광지_카테고리.py [--write]
"""
import sys, os, shutil
from urllib.parse import quote
import openpyxl
from openpyxl.worksheet.hyperlink import Hyperlink

XLSX=r'D:\01.프로젝트\DB수집\작업파일\광역_사이트맵\충청남도\8.서산시\충청남도_서산시.xlsx'
BASE='https://www.seosan.go.kr/www/selectBbsNttList.do?key=2980&bbsNo=617&integrDeptCode=&searchCnd=all&searchKrwd=&searchCtgry='
CATS=[('아라메길',3),('해미읍성',1),('버드랜드',1),('삼길포항',1),('기타',5)]

def main():
    write='--write' in sys.argv
    wb=openpyxl.load_workbook(XLSX); ws=wb.active
    # 관광지 행 찾기 (bbsNo=617, G=관광지)
    pr=None
    for r in range(3,ws.max_row+1):
        K=ws.cell(r,11).value
        if isinstance(K,str) and 'bbsNo=617' in K and ws.cell(r,7).value=='관광지':
            pr=r; break
    if pr is None: print('관광지 행 못찾음'); return
    print(f'관광지 부모행 r{pr} (G=관광지 M={ws.cell(pr,13).value})')
    C=ws.cell(pr,3).value; N=ws.cell(pr,14).value  # 서산시 / 어문,이미지
    n=len(CATS); ins=pr+1
    if not write:
        print(f'[DRY] r{ins}부터 {n}행 삽입 예정:')
        for cat,cnt in CATS: print(f'   H=%s 게시판 M=%d'%(cat,cnt))
        print(f'   G병합 G{pr}:G{pr+n}, D/E스패닝 +{n} 연장, C={C} N={N}')
        return
    shutil.copy(XLSX, XLSX.replace('.xlsx','_backup_관광지카테고리전.xlsx'))
    # 1) 병합 백업+해제 (재매핑 위해)
    ranges=[(m.min_col,m.min_row,m.max_col,m.max_row) for m in list(ws.merged_cells.ranges)]
    for m in list(ws.merged_cells.ranges): ws.unmerge_cells(str(m))
    # 2) 행 삽입
    ws.insert_rows(ins, n)
    # 3) 새 행 채움 (H=col8)
    for i,(cat,cnt) in enumerate(CATS):
        r=ins+i
        ws.cell(r,3).value=C
        ws.cell(r,8).value=cat
        url=BASE+quote(cat)
        ws.cell(r,11).value=url
        ws.cell(r,12).value='게시판'; ws.cell(r,13).value=cnt; ws.cell(r,14).value=N
        ws.row_dimensions[r].height=15
    # 4) 병합 재매핑
    from openpyxl.utils import get_column_letter
    def shift(mc,mr,xc,xr):
        if mr>=ins: mr+=n; xr+=n
        elif xr>=ins: xr+=n
        return mc,mr,xc,xr
    for mc,mr,xc,xr in ranges:
        a,b,c2,d=shift(mc,mr,xc,xr)
        ws.merge_cells(start_row=b,start_column=a,end_row=d,end_column=c2)
    # 5) G(관광지) 병합 추가: pr:pr+n
    ws.merge_cells(start_row=pr,start_column=7,end_row=pr+n,end_column=7)
    # 6) 하이퍼링크 전체 재구성 (K=col11, http값에 링크)
    for r in range(3,ws.max_row+1):
        v=ws.cell(r,11).value
        cell=ws.cell(r,11)
        if isinstance(v,str) and v.startswith('http'):
            cell.hyperlink=Hyperlink(ref=cell.coordinate, target=v)
        else:
            cell.hyperlink=None
    wb.save(XLSX)
    print(f'적용: r{ins}~{ins+n-1} {n}행 삽입·G{pr}:{pr+n} 병합·하이퍼링크 재구성·백업')

if __name__=='__main__': main()
