# -*- coding: utf-8 -*-
"""지오영 DataCart API 테스트"""

import requests
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_datacart():
    print("1. 로그인 중...")
    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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    })
    
    # 2. 장바구니 추가 테스트
    print("\n2. 장바구니 추가 테스트...")
    start = time.time()
    
    resp = session.post('https://gwn.geoweb.kr/Home/DataCart/add', data={
        'productCode': '643104281',  # 하일렌플러스
        'moveCode': '',
        'orderQty': 1
    })
    
    print(f"   소요시간: {time.time()-start:.1f}초")
    print(f"   상태코드: {resp.status_code}")
    print(f"   응답: {resp.text[:500]}")
    
    # JSON 파싱
    try:
        result = resp.json()
        print(f"   result: {result.get('result')}")
        print(f"   msg: {result.get('msg')}")
    except:
        pass
    
    # 3. 장바구니 조회
    print("\n3. 장바구니 조회...")
    cart_resp = session.post('https://gwn.geoweb.kr/Home/PartialProductCart')
    print(f"   응답 길이: {len(cart_resp.text)}")
    
    # 장바구니에 상품 있는지 확인
    if '643104281' in cart_resp.text or '하일렌' in cart_resp.text:
        print("   ✓ 장바구니에 상품 추가됨!")
    else:
        print("   ? 장바구니 확인 필요")

if __name__ == "__main__":
    test_datacart()
