# -*- coding: utf-8 -*-
"""14곳 잔존 빈행 정리 + 현황판(공공기관2_작업현황.xlsx) 행수·상태 갱신."""
import io, os, sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
import openpyxl

BASE = r"D:\01.프로젝트\DB수집\작업파일\공공기관2"
STATUS = os.path.join(BASE, "공공기관2_작업현황.xlsx")

INSTS = [
    (1, "한국전기안전공사"), (2, "한국전력거래소"), (3, "한국조세재정연구원"),
    (4, "한국조폐공사"), (5, "한국주택금융공사"), (6, "한국중부발전"),
    (7, "한국지능정보사회진흥원"), (8, "한국지식재산보호원"), (9, "한국지식재산연구원"),
    (10, "한국지역난방공사"), (11, "한국직업능력연구원"), (12, "한국철도공사"),
    (13, "한국청소년상담복지개발원"), (14, "한국청소년정책연구원"), (15, "한국청소년활동진흥원"),
    (16, "한국체육산업개발"), (17, "한국치산기술협회"),
]
BLOCKED = {3, 4}

rowcounts = {}
for num, name in INSTS:
    fp = os.path.join(BASE, f"{num}.{name}", f"{name}.xlsx")
    if not os.path.exists(fp):
        rowcounts[num] = 0; continue
    wb = openpyxl.load_workbook(fp)
    ws = wb.active
    # 마지막 B(순번) 채워진 행
    last = 2
    for r in range(3, ws.max_row + 1):
        if ws.cell(r, 2).value is not None:
            last = r
    data_rows = last - 2
    # 잔존 빈행 삭제
    if ws.max_row > last:
        # 병합 해제(삭제범위에 걸친 것)
        for m in list(ws.merged_cells.ranges):
            if m.min_row > last:
                ws.unmerge_cells(str(m))
        ws.delete_rows(last + 1, ws.max_row - last)
        wb.save(fp)
    rowcounts[num] = data_rows
    print(f"  {num}.{name}: {data_rows}행" + (" (정리)" if True else ""))

# 현황판 갱신
swb = openpyxl.load_workbook(STATUS)
sh = swb["현황"]
for i, (num, name) in enumerate(INSTS, start=2):
    rc = rowcounts.get(num, 0)
    if num in BLOCKED:
        sh.cell(i, 5, "미수집")  # 상태
        sh.cell(i, 6, "미검수")  # 검수
        cur = sh.cell(i, 11).value or ""
        if "차단" not in cur:
            sh.cell(i, 11, cur + " / ⚠️작업PC 접속차단(2026-06-16)·내일 재시도")
    else:
        sh.cell(i, 5, "✅ 수집완료")
        sh.cell(i, 6, "미검수")
        sh.cell(i, 7, rc)  # 행수
swb.save(STATUS)
print("\n현황판 갱신 완료:", STATUS)
print("수집완료 14곳 총행수:", sum(v for k, v in rowcounts.items() if k not in BLOCKED))
