# -*- coding: utf-8 -*-
"""정읍 N전용 재판정 (r22~끝). _정읍_LN의 media/detail 재사용. L/M 불변, N만 갱신.
사용: python -X utf8 _정읍_N.py [--write]
"""
import sys, os, shutil, importlib.util
from concurrent.futures import ThreadPoolExecutor, as_completed
import openpyxl
HERE=os.path.dirname(os.path.abspath(__file__))
LN=importlib.util.module_from_spec(importlib.util.spec_from_file_location('ln',os.path.join(HERE,'_정읍_LN.py')))
importlib.util.spec_from_file_location('ln',os.path.join(HERE,'_정읍_LN.py')).loader.exec_module(LN)
M=LN.M; XLSX=LN.XLSX; START=22
def judgeN(K,L):
    soup=None
    for _ in range(3):
        soup=M.fetch(LN.SESS,K)
        if soup is not None: break
    if soup is None: return None
    b=M.get_body(soup,M.BODY_SEL); txt=b.get_text(' ',strip=True)
    img,vid,aud,t=LN.media(b)
    if L=='게시판':
        dus=LN.detail_urls(b,K,10)
        if not dus and (LN.EMPTY.search(txt) or not t): return '없음'
        for du in dus:
            ds=M.fetch(LN.SESS,du)
            if not ds: continue
            db=M.get_body(ds,M.BODY_SEL); i2,v2,a2,t2=LN.media(db); img=img or i2;vid=vid or v2;aud=aud or a2;t=t or t2
    return LN.njoin(t,img,vid,aud)
def main():
    write='--write' in sys.argv
    wb=openpyxl.load_workbook(XLSX); ws=wb.active
    jobs=[(r,ws.cell(r,11).value,ws.cell(r,12).value) for r in range(START,ws.max_row+1)
          if isinstance(ws.cell(r,11).value,str) and ws.cell(r,11).value.startswith('http') and ws.cell(r,12).value in ('페이지','게시판')]
    res={}
    with ThreadPoolExecutor(max_workers=6) as ex:
        futs={ex.submit(judgeN,K,L):r for r,K,L in jobs}
        for f in as_completed(futs):
            r=futs[f]
            try: res[r]=f.result()
            except: res[r]=None
    chg=[(r,ws.cell(r,14).value,n) for r,n in sorted(res.items()) if n and n!=(ws.cell(r,14).value or '')]
    print('N변경 %d행:'%len(chg))
    for r,o,n in chg[:60]: print('  r%d %s: %s→%s'%(r,ws.cell(r,7).value or ws.cell(r,6).value,o,n))
    if write and chg:
        shutil.copy(XLSX,XLSX.replace('.xlsx','_backup_N재판정전.xlsx'))
        for r,o,n in chg: ws.cell(r,14).value=n
        wb.save(XLSX); print('적용 %d행'%len(chg))
if __name__=='__main__': main()
