# -*- coding: utf-8 -*-
"""지오영 검색 → 장바구니 추가 테스트"""

import requests
from bs4 import BeautifulSoup
import asyncio
from playwright.async_api import async_playwright
import time
import re

async def get_cookies():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        page = await browser.new_page()
        
        await page.goto('https://gwn.geoweb.kr/Member/Login')
        await page.fill('input[type="text"]', '7390')
        await page.fill('input[type="password"]', 'trajet6640')
        await page.click('button, input[type="submit"]')
        await page.wait_for_load_state('networkidle')
        
        cookies = await page.context.cookies()
        await browser.close()
        return cookies

def test():
    print("1. 로그인...")
    cookies = asyncio.run(get_cookies())
    
    session = requests.Session()
    for c in cookies:
        session.cookies.set(c['name'], c['value'])
    
    session.headers.update({
        'User-Agent': 'Mozilla/5.0',
        'X-Requested-With': 'XMLHttpRequest'
    })
    
    # 2. 검색
    print("\n2. 제품 검색 (661700390 - 콩코르정)...")
    search_resp = session.post('https://gwn.geoweb.kr/Home/PartialSearchProduct', data={
        'srchText': '661700390'
    })
    
    soup = BeautifulSoup(search_resp.text, 'html.parser')
    
    # 제품 코드 찾기 - data 속성이나 hidden input에서
    rows = soup.find_all('tr')
    print(f"   테이블 행: {len(rows)}개")
    
    # HTML 구조 분석
    for row in rows[:2]:
        tds = row.find_all('td')
        if tds:
            print(f"   TD 개수: {len(tds)}")
            for i, td in enumerate(tds[:8]):
                text = td.get_text(strip=True)[:30]
                onclick = td.get('onclick', '')[:50]
                data_attrs = {k:v for k,v in td.attrs.items() if k.startswith('data')}
                print(f"     [{i}] {text} | onclick={onclick} | data={data_attrs}")
    
    # onclick에서 제품 코드 추출
    onclick_pattern = re.findall(r"onclick=['\"]([^'\"]+)['\"]", search_resp.text)
    for oc in onclick_pattern[:3]:
        print(f"   onclick: {oc[:100]}")
    
    # SelectProduct 함수 호출에서 인덱스 확인
    select_pattern = re.findall(r'SelectProduct\s*\(\s*(\d+)', search_resp.text)
    print(f"   SelectProduct 인덱스: {select_pattern[:3]}")
    
    # div-product-detail에서 제품 코드 찾기
    product_divs = soup.find_all('div', class_='div-product-detail')
    print(f"   product-detail divs: {len(product_divs)}")
    
    for div in product_divs[:2]:
        lis = div.find_all('li')
        if lis:
            print(f"   li 개수: {len(lis)}")
            for i, li in enumerate(lis[:5]):
                print(f"     [{i}] {li.get_text(strip=True)[:50]}")

if __name__ == "__main__":
    test()
