# -*- coding: utf-8 -*-
import sys,io,openpyxl,glob,os,re
sys.stdout=io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
from collections import Counter
base=r"D:\01.프로젝트\DB수집\작업파일\공공기관3"
rows=[]
tot=0
for d in sorted(glob.glob(os.path.join(base,"*.*")),key=lambda x:int(re.match(r"(\d+)\.",os.path.basename(x)).group(1)) if re.match(r"\d+\.",os.path.basename(x)) else 999):
    if not os.path.isdir(d): continue
    m=re.match(r"(\d+)\.(.+)",os.path.basename(d))
    if not m: continue
    num,name=int(m.group(1)),m.group(2)
    f=os.path.join(d,name+".xlsx")
    if not os.path.exists(f): 
        rows.append((num,name,'파일없음')); continue
    wb=openpyxl.load_workbook(f); ws=wb.active
    N=ws.max_row; last=2
    for r in range(3,N+1):
        if ws.cell(r,2).value is not None: last=r
    L=Counter(ws.cell(r,12).value for r in range(3,last+1))
    bs=[ws.cell(r,2).value for r in range(3,last+1)]
    seq=bs==list(range(1,len(bs)+1))
    # overlap check
    cells={}; overlap=0
    for mr in ws.merged_cells.ranges:
        for r in range(mr.min_row,mr.max_row+1):
            for c in range(mr.min_col,mr.max_col+1):
                if (r,c) in cells: overlap+=1
                cells[(r,c)]=1
    klink=sum(1 for r in range(3,last+1) if ws.cell(r,11).value and (not ws.cell(r,11).hyperlink or ws.cell(r,11).hyperlink.target!=ws.cell(r,11).value))
    tail=N-last
    tot+=last-2
    flag=[]
    if not seq: flag.append('B비연속')
    if overlap: flag.append(f'병합겹침{overlap}')
    if klink: flag.append(f'K링크{klink}')
    if tail: flag.append(f'후행{tail}')
    rows.append((num,name,last-2,dict(L),'OK' if not flag else ' '.join(flag)))
for r in rows:
    if len(r)==5:
        print(f"{r[0]:2}.{r[1]:18} {r[2]:4}행 L={r[3]} → {r[4]}")
    else: print(r)
print(f"\n총 데이터행: {tot}")
