# -*- coding: utf-8 -*-
import openpyxl, io
from collections import defaultdict
wb=openpyxl.load_workbook("한국지역난방공사.xlsx"); ws=wb.active
out=io.open("_effdup_out.txt","w",encoding="utf-8")
def w(*a): out.write(" ".join(str(x) for x in a)+"\n")
# build effective D..J by filling down using merged ranges
# approach: for each column D..J(4..10), fill blanks downward ONLY within merged spans
# Simpler: replicate merged top-left value across the merge range
eff={}  # (r,c)->value
for r in range(3,ws.max_row+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 epath(r):
    return tuple((str(eff[(r,c)]).strip() if eff[(r,c)] not in(None,"") else "") for c in range(4,11))
def leaf(r):
    p=[x for x in epath(r) if x]
    return p[-1] if p else ""
# duplicate leaf NAME
byleaf=defaultdict(list)
for r in range(3,ws.max_row+1):
    byleaf[leaf(r)].append(r)
w("=== rows sharing a leaf menu name (effective path) ===")
for nm,rs in sorted(byleaf.items()):
    if len(rs)>1 and nm:
        w("LEAF:",nm,"  rows:",rs)
        for rr in rs:
            fp=" > ".join(x for x in epath(rr) if x)
            w("   r%d B%s L=%s M=%s N=%s"%(rr,ws.cell(rr,2).value,ws.cell(rr,12).value,ws.cell(rr,13).value,ws.cell(rr,14).value))
            w("        path:",fp)
            w("        K:",ws.cell(rr,11).value)
        w("")
out.close(); print("done")
