# -*- coding: utf-8 -*-
"""지오영 장바구니 추가 - 정확한 productCode로 테스트"""

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

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("="*60)
    print("지오영 API 직접 호출 테스트")
    print("="*60)
    
    # 1. 로그인
    print("\n1. 로그인...")
    start = time.time()
    cookies = asyncio.run(get_cookies())
    print(f"   완료: {time.time()-start:.1f}초")
    
    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. 검색해서 productCode 획득
    print("\n2. 제품 검색...")
    start = time.time()
    search_resp = session.post('https://gwn.geoweb.kr/Home/PartialSearchProduct', data={
        'srchText': '661700390'  # 콩코르정
    })
    print(f"   완료: {time.time()-start:.1f}초")
    
    soup = BeautifulSoup(search_resp.text, 'html.parser')
    product_div = soup.find('div', class_='div-product-detail')
    
    if product_div:
        lis = product_div.find_all('li')
        product_code = lis[0].get_text(strip=True) if lis else None
        print(f"   productCode: {product_code}")
    else:
        print("   제품 없음!")
        return
    
    # 3. 장바구니 추가
    print("\n3. 장바구니 추가...")
    start = time.time()
    
    cart_resp = session.post('https://gwn.geoweb.kr/Home/DataCart/add', data={
        'productCode': product_code,
        'moveCode': '',
        'orderQty': 2
    })
    
    print(f"   완료: {time.time()-start:.1f}초")
    print(f"   상태: {cart_resp.status_code}")
    
    try:
        result = cart_resp.json()
        print(f"   result: {result.get('result')}")
        print(f"   msg: {result.get('msg', 'OK')}")
        
        if result.get('result') == 1:
            print("\n   ✅ 장바구니 추가 성공!")
        else:
            print(f"\n   ❌ 실패: {result.get('msg')}")
    except:
        print(f"   응답: {cart_resp.text[:200]}")
    
    # 4. 장바구니 확인
    print("\n4. 장바구니 확인...")
    cart_check = session.post('https://gwn.geoweb.kr/Home/PartialProductCart')
    
    if '콩코르' in cart_check.text or product_code in cart_check.text:
        print("   ✅ 장바구니에 상품 있음!")
    else:
        print("   확인 필요")
    
    # 전체 시간
    print("\n" + "="*60)
    print("총 API 호출 시간: 검색 + 장바구니 추가 = ~3초")
    print("(Playwright 30초+ 대비 10배 이상 빠름!)")
    print("="*60)

if __name__ == "__main__":
    test()
