import sys, io, os, shutil
from copy import copy
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
import openpyxl
from openpyxl.utils import get_column_letter

PKG = r'D:\01.프로젝트\DB수집\작업파일\_제출패키지_2026-06-03\프리랜서1\충청남도_부여군.xlsx'
WRK = r'D:\01.프로젝트\DB수집\작업파일\광역_사이트맵\충청남도\7.부여군\충청남도_부여군.xlsx'
TEMPLATE_ROW = 233
X_COL = 24  # column X = intentional separator gap (borderless)

def anyb(cell):
    b = cell.border
    return any([b.left.style, b.right.style, b.top.style, b.bottom.style])

def fix(path):
    BK = path.replace('.xlsx', '_backup_테두리보정전.xlsx')
    if not os.path.exists(BK):
        shutil.copy2(path, BK)
    wb = openpyxl.load_workbook(path); ws = wb.active
    # template borders per column from row 233
    tmpl = {c: ws.cell(TEMPLATE_ROW, c).border for c in range(1, ws.max_column + 1)}
    # set of cells inside any merge (>=3)
    merged = set()
    for m in ws.merged_cells.ranges:
        if m.min_row >= 3:
            for rr in range(m.min_row, m.max_row + 1):
                for cc in range(m.min_col, m.max_col + 1):
                    merged.add((rr, cc))
    fixes = {}
    for r in range(3, ws.max_row + 1):
        for c in range(2, ws.max_column + 1):
            if c == X_COL:           # skip intentional separator
                continue
            if (r, c) in merged:     # skip merge interiors/anchors
                continue
            cell = ws.cell(r, c)
            if not anyb(cell):       # only fill genuinely borderless cells
                cell.border = copy(tmpl[c])
                fixes[get_column_letter(c)] = fixes.get(get_column_letter(c), 0) + 1
    wb.save(path)
    print(f'{os.path.basename(path)}: 테두리 채움 {sum(fixes.values())}셀  by col {fixes}  (backup {os.path.basename(BK)})')
    return path

for p in (PKG, WRK):
    fix(p)

# verify: re-scan missing (non-merge, non-X)
print('\n=== verify (PKG) remaining borderless non-merge non-X ===')
ws = openpyxl.load_workbook(PKG).active
merged = set()
for m in ws.merged_cells.ranges:
    if m.min_row >= 3:
        for rr in range(m.min_row, m.max_row+1):
            for cc in range(m.min_col, m.max_col+1):
                merged.add((rr,cc))
rem = {}
for r in range(3, ws.max_row+1):
    for c in range(2, ws.max_column+1):
        if c==X_COL or (r,c) in merged: continue
        if not anyb(ws.cell(r,c)):
            rem[get_column_letter(c)] = rem.get(get_column_letter(c),0)+1
print('remaining:', rem if rem else 'NONE')
print('K233 vs K137 after fix:',
      ws.cell(233,11).border.left.style, '|', ws.cell(137,11).border.left.style)
