# -*- coding: utf-8 -*-
import sys,io,openpyxl
sys.stdout=io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
from collections import Counter
from openpyxl.utils import range_boundaries
P=r'D:\01.프로젝트\DB수집\작업파일\공공기관3\1.한국원자력환경공단\한국원자력환경공단.xlsx'
wb=openpyxl.load_workbook(P);ws=wb.active
rows=[r for r in range(3,ws.max_row+1) if ws.cell(r,2).value is not None]
END=rows[-1];issues=[]
bs=[ws.cell(r,2).value for r in rows]
if bs!=list(range(1,len(rows)+1)): issues.append(f'B불연속 len{len(rows)} max{max(bs)}')
badC=[r for r in rows if ws.cell(r,3).value!='한국원자력환경공단']
if badC: issues.append(f'C오류 {len(badC)}')
badpage=[ws.cell(r,2).value for r in rows if ws.cell(r,12).value=='페이지' and ws.cell(r,13).value!=1]
if badpage: issues.append(f'페이지M!=1 {badpage}')
badsite=[ws.cell(r,2).value for r in rows if ws.cell(r,12).value=='사이트' and any(ws.cell(r,c).value not in (None,'') for c in (13,14,15,16,17))]
if badsite: issues.append(f'사이트비빈칸 {badsite}')
badboard=[ws.cell(r,2).value for r in rows if ws.cell(r,12).value=='게시판' and ws.cell(r,13).value is None]
if badboard: issues.append(f'게시판M None {badboard}')
merged=[str(m) for m in ws.merged_cells.ranges]
bycol={}
for m in merged:
    c1,r1,c2,r2=range_boundaries(m)
    if c1==c2: bycol.setdefault(c1,[]).append((r1,r2))
overlap=0
for c,rngs in bycol.items():
    rngs.sort()
    for i in range(len(rngs)-1):
        if rngs[i][1]>=rngs[i+1][0]: overlap+=1
if overlap: issues.append(f'병합겹침 {overlap}')
linkmis=0
for r in rows:
    cell=ws.cell(r,11);v=cell.value
    if v and isinstance(v,str) and v.startswith('http'):
        if cell.hyperlink and cell.hyperlink.target and cell.hyperlink.target!=v: linkmis+=1
if linkmis: issues.append(f'K링크불일치 {linkmis}')
print('데이터행수',len(rows),'END',END)
print('L분포',dict(Counter(ws.cell(r,12).value for r in rows)))
print('N분포',dict(Counter(ws.cell(r,14).value for r in rows)))
print('병합수',len(merged))
kogl=sum(1 for r in rows if ws.cell(r,15).value and ws.cell(r,15).value!='미부착')
print('KOGL부착',kogl)
flags=[(ws.cell(r,2).value,ws.cell(r,19).value) for r in rows if ws.cell(r,19).value and ws.cell(r,19).value!='외부링크']
print('비고플래그',len(flags),flags)
print('=== ISSUES ===' if issues else '=== 검증 PASS ===')
for i in issues: print('  ',i)
