# -*- coding: utf-8 -*-
"""22행+ 게시판 상세 렌더해 '공공누리 제N유형' 텍스트 라이선스 검출 → O/P/Q 판정(읽기, 결과 json)."""
import openpyxl, re, json
from playwright.sync_api import sync_playwright
KOGL=re.compile(r'공공누리\s*제?\s*([1-4])\s*유형')
ws=openpyxl.load_workbook('한국조세재정연구원.xlsx').active
targets=[]
for r in range(22,ws.max_row+1):
    if all(ws.cell(r,c).value in (None,'') for c in range(2,16)): continue
    if ws.cell(r,12).value=='게시판':
        lab=ws.cell(r,6).value or ws.cell(r,5).value or ws.cell(r,4).value
        targets.append((r,lab,str(ws.cell(r,11).value)))
print('게시판 대상:',len(targets))
out={}
with sync_playwright() as p:
    b=p.chromium.launch();pg=b.new_page(ignore_https_errors=True)
    for r,lab,url in targets:
        types=set()
        try:
            pg.goto(url,timeout=30000,wait_until='networkidle');pg.wait_for_timeout(700)
            a=pg.query_selector('a[onclick*=fn_]') or pg.query_selector('table tbody tr a') or pg.query_selector('.lst a')
            if a:
                a.click();pg.wait_for_timeout(1500)
                txt=pg.inner_text('body')
                for m in KOGL.finditer(txt): types.add(int(m.group(1)))
            res='없음' if not types else ','.join(f'{t}유형' for t in sorted(types))
        except Exception as e:
            res='ERR:'+str(e)[:25]
        out[r]={'label':lab,'O':res}
        print(f'r{r} {lab[:22]:22} -> {res}')
    b.close()
json.dump(out,open('_kogl_result.json','w',encoding='utf-8'),ensure_ascii=False,indent=1)
