# -*- coding: utf-8 -*-
"""미검수 27곳 C열(사이트명)을 "광역 기관"(공백구분)으로 채움. 검수완료 제외.
사용: python -X utf8 _fill_C_province.py [--write]
"""
import sys, os, re, shutil, importlib.util
import openpyxl

HERE=os.path.dirname(os.path.abspath(__file__))
MODULES=['_chungnam_phase234_all.py','_chungbuk_phase234_all.py','_jeonbuk_phase234_all.py']
TARGETS={'서산시','아산시','천안시','청양군','홍성군',
 '괴산군','단양군','보은군','영동군','옥천군','음성군','제천시','증평군','진천군','청주시','충주시',
 '부안군','순창군','완주군','익산시','임실군','장수군','전주시','정읍시','진안군','서귀포시','제주시'}

def load():
    sites={}
    for f in MODULES:
        sp=importlib.util.spec_from_file_location(f[:-3],os.path.join(HERE,f));m=importlib.util.module_from_spec(sp);sp.loader.exec_module(m)
        sites.update(m.SITES)
    return sites

def province_of(path):
    m=re.search(r'광역_사이트맵[\\/]([^\\/]+)[\\/]',path)
    return m.group(1) if m else '?'

def main():
    write='--write' in sys.argv
    sites=load(); locked=[]; done=[]
    for org in sorted(TARGETS):
        if org not in sites: print(org,'SITES없음'); continue
        xlsx=sites[org]['xlsx']
        prov=province_of(xlsx); newC=f'{prov} {org}'
        wb=openpyxl.load_workbook(xlsx); ws=wb.active
        ch=0
        for r in range(3,ws.max_row+1):
            content = any(ws.cell(r,c).value not in (None,'') for c in (2,4,5,6,7,8,9,10,11,12))
            cur=ws.cell(r,3).value
            if (cur not in (None,'')) or content:
                if cur!=newC:
                    if write: ws.cell(r,3).value=newC
                    ch+=1
        if write and ch:
            try:
                bak=xlsx.replace('.xlsx','_backup_C광역전.xlsx')
                if not os.path.exists(bak): shutil.copy(xlsx,bak)
                wb.save(xlsx)
            except PermissionError:
                locked.append(org); print(f'{org:6} ❌파일열림 (미적용)'); continue
        done.append((org,newC,ch))
        print(f'{org:6} → "{newC}"  변경 {ch}행 {"[적용]" if write else "[DRY]"}')
    if locked: print('\n⚠️ 파일열림으로 미적용:',', '.join(locked))

if __name__=='__main__': main()
