# -*- coding: utf-8 -*-
import openpyxl, io
wb=openpyxl.load_workbook("한국지역난방공사.xlsx"); ws=wb.active
out=io.open("_mergecand_out.txt","w",encoding="utf-8")
def w(*a): out.write(" ".join(str(x) for x in a)+"\n")
COLS={4:'D',5:'E',6:'F',7:'G',8:'H',9:'I',10:'J'}
mx=ws.max_row

# existing merged ranges by (col)->list of (r1,r2)
merged_cols={}
for mr in ws.merged_cells.ranges:
    if mr.min_col==mr.max_col:
        merged_cols.setdefault(mr.min_col,[]).append((mr.min_row,mr.max_row))
def already_merged(c,r1,r2):
    for (a,b) in merged_cols.get(c,[]):
        if a<=r1 and b>=r2: return True
    return False

# literal value
def lit(r,c):
    v=ws.cell(r,c).value
    return str(v).strip() if v not in(None,"") else ""
# effective parent path D..c-1 (fill merged)
eff={}
for r in range(3,mx+1):
    for c in range(4,11): eff[(r,c)]=ws.cell(r,c).value
for mr in ws.merged_cells.ranges:
    if mr.min_col>=4 and mr.max_col<=10:
        v=ws.cell(mr.min_row,mr.min_col).value
        for r in range(mr.min_row,mr.max_row+1):
            for c in range(mr.min_col,mr.max_col+1): eff[(r,c)]=v
def effv(r,c):
    v=eff[(r,c)]; return str(v).strip() if v not in(None,"") else ""
def parentpath(r,c):  # D..c-1 effective
    return tuple(effv(r,cc) for cc in range(4,c))

total=0
for c in range(4,11):
    cand=[]
    r=3
    while r<=mx:
        v=lit(r,c)
        if not v:
            r+=1; continue
        # extend run while next row literal == v AND same parent path
        r2=r
        while r2+1<=mx and lit(r2+1,c)==v and parentpath(r2+1,c)==parentpath(r,c):
            r2+=1
        if r2>r and not already_merged(c,r,r2):
            cand.append((r,r2,v,parentpath(r,c)))
        r=r2+1
    if cand:
        w(f"\n=== column {COLS[c]} — {len(cand)} unmerged repeated-value runs ===")
        for (r1,r2,v,pp) in cand:
            total+=1
            pps=" > ".join(x for x in pp if x)
            w(f"  {COLS[c]}{r1}:{COLS[c]}{r2}  '{v}'   [부모: {pps if pps else '(대분류)'}]  (행 {r1}~{r2}, {r2-r1+1}개)")
w(f"\nTOTAL merge-candidate runs: {total}")
out.close(); print("done total",total)
