import sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
import openpyxl
from openpyxl.utils import get_column_letter
P = r'D:\01.프로젝트\DB수집\작업파일\_제출패키지_2026-06-03\제출_프리랜서1_2026-06-03\충청남도_부여군.xlsx'
ws = openpyxl.load_workbook(P).active
M=list(ws.merged_cells.ranges)
def mof(r,c):
    for m in M:
        if m.min_row<=r<=m.max_row and m.min_col<=c<=m.max_col: return m
    return None
def eff(r,c):
    m=mof(r,c); return ws.cell(m.min_row,m.min_col).value if m else ws.cell(r,c).value
data=[r for r in range(3,ws.max_row+1) if ws.cell(r,2).value not in (None,'')]
dset=set(data)

print('데이터행', len(data), '| 총병합', len(M), '| 헤더병합',
      [h for h in ('B1:R1','S1:W1','Y1:AA1') if h in {str(m) for m in M}])

# 부모 그룹 = 어떤 카테고리 컬럼 c에서, 한 값 아래로 더 깊은 컬럼(c+1..)이 채워진 자식들이 이어지는 경우
# 각 부모그룹의 병합/비병합 상태를 리포트 (c = E5,F6,G7)
def parent_groups(c):
    groups=[]
    i=0
    while i<len(data):
        r=data[i]
        v=ws.cell(r,c).value
        if v in (None,'') or mof(r,c) and mof(r,c).min_row!=r:
            i+=1; continue
        # collect children: following rows with same parent(cols<c) and (c blank or merged-cont) and deeper col filled
        parent=tuple(eff(r,cc) for cc in range(4,c))
        j=i+1; child=0; deeper=False
        rows=[r]
        while j<len(data):
            r2=data[j]
            if tuple(eff(r2,cc) for cc in range(4,c))!=parent: break
            cv=ws.cell(r2,c).value
            m2=mof(r2,c)
            cont = (cv in (None,'')) or (m2 and m2.min_row<r2)   # blank or inside same merge
            if not cont: break
            rows.append(r2); j+=1
        if len(rows)>1:
            # is any deeper column filled in these rows? (so c is a parent)
            if any(ws.cell(rr,c+1).value not in (None,'') for rr in rows):
                m=mof(r,c)
                merged = bool(m and m.max_row>m.min_row)
                groups.append((rows[0],rows[-1],v,merged))
            i=j
        else:
            i+=1
    return groups

for c,nm in [(5,'E'),(6,'F'),(7,'G')]:
    gs=parent_groups(c)
    if not gs: continue
    merged=[g for g in gs if g[3]]; unmerged=[g for g in gs if not g[3]]
    print(f'\n=== {nm}열 부모그룹 {len(gs)}개 (병합 {len(merged)} / 비병합 {len(unmerged)}) ===')
    for a,z,v,mg in gs:
        tag='병합' if mg else '★비병합'
        print(f'  {nm}{a}:{z} [{tag}] {v!r}  (D={eff(a,4)!r} E={eff(a,5)!r} F={eff(a,6)!r})')
