# -*- coding: utf-8 -*-
import openpyxl, re, collections, os, glob
from openpyxl.utils import get_column_letter
d=os.path.dirname(os.path.abspath(__file__))
fn=[p for p in glob.glob(os.path.join(d,'*.xlsx')) if not os.path.basename(p).startswith(('_','~'))][0]
wb=openpyxl.load_workbook(fn); ws=wb.active
issues=[]; warn=[]
if not re.match(r'^\d+_.+', ws.title or ''): issues.append('시트명 형식 '+repr(ws.title))
hm={str(m) for m in ws.merged_cells.ranges}
for h in ['B1:R1','S1:W1','Y1:AA1']:
    if h not in hm: issues.append('헤더병합 누락 '+h)
data=[r for r in range(3,ws.max_row+1) if ws.cell(r,2).value is not None]
n=len(data)
bs=[ws.cell(r,2).value for r in data]
if bs!=list(range(1,n+1)):
    nums=[b for b in bs if isinstance(b,(int,float))]
    s=set(nums); gaps=[i for i in range(1,int(max(nums))+1) if i not in s] if nums else []
    dups=sorted({x for x in nums if nums.count(x)>1})
    issues.append('B순번 비연속(행수%d max%s 빠진%s 중복%s)'%(n,max(nums) if nums else None,gaps[:10],dups[:5]))
if [r for r in data if not ws.cell(r,3).value]: issues.append('C 빈칸 %d'%len([r for r in data if not ws.cell(r,3).value]))
fv={r:{c:ws.cell(r,c).value for c in (4,5,6)} for r in data}
for mr in ws.merged_cells.ranges:
    if mr.min_col in (4,5,6) and mr.min_row>=3:
        top=ws.cell(mr.min_row,mr.min_col).value
        for rr in range(mr.min_row,mr.max_row+1):
            if rr in fv: fv[rr][mr.min_col]=top
for mr in ws.merged_cells.ranges:
    if mr.min_row<3: continue
    rows=range(mr.min_row,mr.max_row+1)
    if mr.min_col==5 and len({fv[r][4] for r in rows if r in fv})>1: issues.append('E병합 D경계초과 '+str(mr))
    if mr.min_col==6 and len({(fv[r][4],fv[r][5]) for r in rows if r in fv})>1: issues.append('F병합 DE경계초과 '+str(mr))
for r in data:
    k=ws.cell(r,11).value
    if not k or 'javascript' in str(k).lower() or str(k).strip()=='#': issues.append('K이상 r%d'%r)
rg=[m for m in ws.merged_cells.ranges if m.min_row>=3]
ov=[(str(rg[i]),str(rg[j])) for i in range(len(rg)) for j in range(i+1,len(rg)) if not(rg[i].max_row<rg[j].min_row or rg[j].max_row<rg[i].min_row or rg[i].max_col<rg[j].min_col or rg[j].max_col<rg[i].min_col)]
if ov: issues.append('병합겹침 %d %s'%(len(ov),ov[:2]))
for r in data:
    L=ws.cell(r,12).value
    if L=='사이트':
        dirty=[get_column_letter(c) for c in (13,14,15,16,17) if ws.cell(r,c).value not in (None,'')]
        if dirty: warn.append('사이트행 r%d %s'%(r,dirty))
    elif L=='게시판' and ws.cell(r,13).value in (None,0,''): warn.append('게시판 M빈/0 r%d'%r)
    elif L not in ('페이지','게시판','사이트'): issues.append('L이상 r%d=%r'%(r,L))
hc=sum(1 for r in data if ws.cell(r,11).hyperlink)
print('FILE:', os.path.basename(fn))
print('행수 %d · 하이퍼링크 %d · 병합 %d · L %s'%(n,hc,len(rg),dict(collections.Counter(ws.cell(r,12).value for r in data))))
print('ISSUES(%d):'%len(issues))
for i in issues: print('  X',i)
print('WARN(%d, 내용검수영역):'%len(warn))
for w in warn[:25]: print('  !',w)
print('RESULT:', 'PASS' if not issues else 'FAIL')
