# -*- coding: utf-8 -*-
import openpyxl, io
from openpyxl.utils.cell import range_boundaries
wb=openpyxl.load_workbook("한국임업진흥원.xlsx")
ws=wb.active
out=io.open("_verify_out.txt","w",encoding="utf-8")
def P(*a): out.write(" ".join(str(x) for x in a)+"\n")
MAXR=ws.max_row
P("max_row",MAXR)
# B continuity
bs=[ws.cell(r,2).value for r in range(3,MAXR+1)]
exp=list(range(1,len(bs)+1))
P("B contiguous 1..N:", bs==exp, "Bmax",bs[-1])
# merge overlap + bounds
cells={}; overlap=0; outofDJ=0
for m in ws.merged_cells.ranges:
    s=str(m)
    if s in ("B1:R1","S1:W1","Y1:AA1"): continue
    c1,r1,c2,r2=range_boundaries(s)
    if not(4<=c1<=10 and 4<=c2<=10): outofDJ+=1; P("  OOB merge",s)
    for r in range(r1,r2+1):
        for c in range(c1,c2+1):
            if (r,c) in cells: overlap+=1
            cells[(r,c)]=s
P("merge overlaps:",overlap,"out-of-DJ:",outofDJ,"total data merges:",len(ws.merged_cells.ranges)-3)
# DEF holes: each row D..leaf contiguous; merged cells count as filled
filled={}
for m in ws.merged_cells.ranges:
    c1,r1,c2,r2=range_boundaries(str(m))
    top=ws.cell(r1,c1).value
    for r in range(r1,r2+1):
        for c in range(c1,c2+1): filled[(r,c)]=top
def gv(r,c):
    v=filled.get((r,c),ws.cell(r,c).value); return v if (v is not None and str(v).strip()!="") else None
holes=0; nok=0; noK=0
for r in range(3,MAXR+1):
    vals=[gv(r,c) for c in range(4,11)]
    leaf=-1
    for i,v in enumerate(vals):
        if v is not None: leaf=i
    # contiguity D..leaf
    for i in range(0,leaf+1):
        if vals[i] is None: holes+=1; P("  HOLE r",r,"col",4+i,vals); break
    # K present on leaf rows? (allow site rows w/ K; flag empty K)
    k=ws.cell(r,11).value
    if not k or not str(k).strip():
        noK+=1; P("  noK r",r,vals)
    else:
        # hyperlink matches value
        hl=ws.cell(r,11).hyperlink
        if hl and str(hl.target).strip()!=str(k).strip(): nok+=1; P("  K mismatch r",r,k,hl.target)
P("DEF holes:",holes,"K-hyperlink mismatch:",nok,"empty-K rows:",noK)
# dump sample groups
P("\n--- sample rows ---")
for r in list(range(3,18))+list(range(95,118)):
    if r>MAXR: break
    vv=[]
    for c in range(2,18):
        v=ws.cell(r,c).value
        if v is not None and str(v).strip()!="": vv.append("%s=%s"%(openpyxl.utils.get_column_letter(c),v))
    P(r," | ".join(vv))
out.close(); print("done")
