# -*- coding: utf-8 -*-
import sys,io,json
sys.stdout=io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
    br=p.chromium.launch(headless=True)
    ctx=br.new_context(ignore_https_errors=True,viewport={'width':1920,'height':1080})
    pg=ctx.new_page()
    pg.goto("https://www.nypi.re.kr/",wait_until='domcontentloaded',timeout=40000); pg.wait_for_timeout(2500)
    # 전체메뉴/메가메뉴 펼침 시도
    for sel in ['button:has-text("전체메뉴")','.allmenu','.btn_all','a:has-text("전체")']:
        try:
            e=pg.query_selector(sel)
            if e: e.click(timeout=1500); pg.wait_for_timeout(800); break
        except: pass
    r=pg.evaluate(r"""()=>{
      // GNB 대분류>중분류 추출
      function txt(a){return (a.textContent||'').trim().replace(/\s+/g,' ');}
      let out=[];
      // 후보 네비 컨테이너
      const conts=[...document.querySelectorAll('nav,.gnb,#gnb,header ul,.allmenu,.menu')];
      let best=null,bn=0;
      for(const c of conts){const n=c.querySelectorAll('a').length; if(n>bn){bn=n;best=c;}}
      if(!best) return out;
      best.querySelectorAll(':scope ul > li').forEach(li=>{
        const a=li.querySelector('a'); if(a&&txt(a)) out.push(txt(a));
      });
      return out.slice(0,40);
    }""")
    print(json.dumps(r,ensure_ascii=False))
    br.close()
