# -*- coding: utf-8 -*-
import os, copy
import openpyxl
from openpyxl.styles import Font, PatternFill, Border, Side, Alignment

ROOT = r"D:\01.프로젝트\DB수집"
TEMPLATE = os.path.join(ROOT, "자료_취합_예시.xlsx")
BASE = os.path.join(ROOT, "작업파일", "공공기관3")
os.makedirs(BASE, exist_ok=True)

# (새번호, 기관명, 베이스URL, 마스터번호, 부처)  -- 한국저작권위원회(276) 제외
INSTS = [
    (1,  "한국원자력환경공단",     "https://www.korad.or.kr/",          261, "기후에너지환경부"),
    (2,  "한국의료분쟁조정중재원", "https://www.k-medi.or.kr/",         262, "보건복지부"),
    (3,  "한국의약품안전관리원",   "https://www.drugsafe.or.kr/",       263, "식품의약품안전처"),
    (4,  "한국인터넷진흥원",       "https://www.kisa.or.kr/",           264, "과학기술정보통신부"),
    (5,  "한국임업진흥원",         "https://www.kofpi.or.kr/",          265, "산림청"),
    (6,  "한국자산관리공사",       "https://www.kamco.or.kr/",          266, "금융위원회"),
    (7,  "한국잡월드",             "https://www.koreajobworld.or.kr/",  267, "고용노동부"),
    (8,  "한국장기조직기증원",     "https://www.koda1458.kr/",          269, "보건복지부"),
    (9,  "한국장애인개발원",       "https://www.koddi.or.kr/",          270, "보건복지부"),
    (10, "한국장애인고용공단",     "https://www.kead.or.kr/",           271, "고용노동부"),
    (11, "한국장학재단",           "https://www.kosaf.go.kr/",          272, "교육부"),
    (12, "한국재정정보원",         "https://www.fis.kr/",               274, "기획재정부"),
    (13, "한국저작권보호원",       "https://www.kcopa.or.kr/",          275, "문화체육관광부"),
]

# ---- 템플릿 헤더(행1~2) 로드 ----
tw = openpyxl.load_workbook(TEMPLATE)
tws = tw.active
MERGES = ['B1:R1', 'S1:W1', 'Y1:AA1']
COLW = {}
for k, v in tws.column_dimensions.items():
    if v.width:
        COLW[k] = v.width
RH = {1: tws.row_dimensions[1].height, 2: tws.row_dimensions[2].height}

def build_inst_xlsx(num, name):
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "%02d_%s" % (num, name)
    for r in (1, 2):
        for c in range(1, 28):
            s = tws.cell(r, c)
            d = ws.cell(r, c)
            d.value = s.value
            if s.has_style:
                d.font = copy.copy(s.font)
                d.fill = copy.copy(s.fill)
                d.border = copy.copy(s.border)
                d.alignment = copy.copy(s.alignment)
                d.number_format = s.number_format
                d.protection = copy.copy(s.protection)
    for m in MERGES:
        ws.merge_cells(m)
    for k, w in COLW.items():
        ws.column_dimensions[k].width = w
    for rr, hh in RH.items():
        if hh:
            ws.row_dimensions[rr].height = hh
    ws.freeze_panes = "A3"
    return wb

made = []
for num, name, url, mnum, dept in INSTS:
    folder = os.path.join(BASE, "%d.%s" % (num, name))
    os.makedirs(folder, exist_ok=True)
    fpath = os.path.join(folder, "%s.xlsx" % name)
    if not os.path.exists(fpath):
        wb = build_inst_xlsx(num, name)
        wb.save(fpath)
        made.append(fpath)
    else:
        made.append(fpath + " (이미있음·skip)")

# ---- 현황판 공공기관3_작업현황.xlsx ----
STATUS = os.path.join(BASE, "공공기관3_작업현황.xlsx")
thin = Side(style="thin", color="BFBFBF")
border = Border(left=thin, right=thin, top=thin, bottom=thin)
hdr_fill = PatternFill("solid", fgColor="D9E1F2")
hdr_font = Font(bold=True, size=10)
center = Alignment(horizontal="center", vertical="center")
left = Alignment(horizontal="left", vertical="center")

swb = openpyxl.Workbook()
sh = swb.active
sh.title = "현황"
cols = ["구분","번호","기관","담당자","상태","검수","행수","검수완료일","제출완료","제출일","비고","홈페이지"]
for c, h in enumerate(cols, 1):
    cell = sh.cell(1, c, h)
    cell.fill = hdr_fill; cell.font = hdr_font; cell.alignment = center; cell.border = border
for i, (num, name, url, mnum, dept) in enumerate(INSTS, start=2):
    row = ["공공기관", num, name, "프리랜서2", "미수집", "미검수", "", "", "", "",
           "마스터번호 %d / %s" % (mnum, dept), url]
    for c, val in enumerate(row, 1):
        cell = sh.cell(i, c, val)
        cell.border = border
        cell.alignment = left if c in (3, 11, 12) else center
        if c == 12 and val:
            cell.hyperlink = val
            cell.font = Font(color="0000FF", underline="single", size=10)
widths = {"A":9,"B":6,"C":24,"D":10,"E":10,"F":8,"G":7,"H":12,"I":9,"J":11,"K":30,"L":30}
for k, w in widths.items():
    sh.column_dimensions[k].width = w
sh.freeze_panes = "A2"

# 요약 시트
su = swb.create_sheet("요약")
last = 1 + len(INSTS)
su["A1"] = "◆ 담당자별"; su["A1"].font = Font(bold=True)
hdr = ["담당자","기관수","검수완료","미검수","제출완료","총 행수"]
for c, h in enumerate(hdr, 1):
    cell = su.cell(2, c, h); cell.font = hdr_font; cell.fill = hdr_fill; cell.alignment = center; cell.border = border
su["A3"] = "프리랜서2"
su["B3"] = '=COUNTIF(현황!$D$2:$D$%d,A3)' % last
su["C3"] = '=COUNTIFS(현황!$D$2:$D$%d,A3,현황!$F$2:$F$%d,"완료")' % (last, last)
su["D3"] = '=COUNTIFS(현황!$D$2:$D$%d,A3,현황!$F$2:$F$%d,"미검수")' % (last, last)
su["E3"] = '=COUNTIFS(현황!$D$2:$D$%d,A3,현황!$I$2:$I$%d,"완료")' % (last, last)
su["F3"] = '=SUMIFS(현황!$G$2:$G$%d,현황!$D$2:$D$%d,A3)' % (last, last)
su["A5"] = "◆ 전체"; su["A5"].font = Font(bold=True)
su["A6"] = "기관수"; su["B6"] = '=COUNTA(현황!$B$2:$B$%d)' % last
su["A7"] = "검수완료"; su["B7"] = '=COUNTIF(현황!$F$2:$F$%d,"완료")' % last
su["A8"] = "총 행수"; su["B8"] = '=SUM(현황!$G$2:$G$%d)' % last
for k, w in {"A":12,"B":12,"C":10,"D":8,"E":10,"F":10}.items():
    su.column_dimensions[k].width = w
swb.save(STATUS)

print("=== 생성 완료 ===")
print("폴더/엑셀:", len(made))
for m in made:
    print("  ", os.path.relpath(m, ROOT))
print("현황판:", os.path.relpath(STATUS, ROOT))
