# -*- coding: utf-8 -*-
"""장바구니 조회 API 테스트"""

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

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)
    
    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'
    })
    
    # 1. 먼저 제품 하나 담기
    print("\n1. 테스트용 제품 담기...")
    search_resp = session.post('https://gwn.geoweb.kr/Home/PartialSearchProduct', 
                                data={'srchText': '661700390'})
    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')
        internal_code = lis[0].get_text(strip=True)
        
        cart_resp = session.post('https://gwn.geoweb.kr/Home/DataCart/add', data={
            'productCode': internal_code,
            'moveCode': '',
            'orderQty': 3
        })
        print(f"   담기 결과: {cart_resp.json()}")
    
    # 2. 장바구니 조회
    print("\n2. 장바구니 조회 (PartialProductCart)...")
    cart_resp = session.post('https://gwn.geoweb.kr/Home/PartialProductCart')
    print(f"   상태: {cart_resp.status_code}")
    print(f"   길이: {len(cart_resp.text)}")
    
    # HTML 파싱
    soup = BeautifulSoup(cart_resp.text, 'html.parser')
    
    # 테이블 찾기
    tables = soup.find_all('table')
    print(f"   테이블 수: {len(tables)}")
    
    # 장바구니 항목 파싱
    cart_items = []
    
    # div_cart_detail 클래스 찾기
    cart_divs = soup.find_all('div', class_='div_cart_detail')
    print(f"   cart_detail divs: {len(cart_divs)}")
    
    for div in cart_divs:
        lis = div.find_all('li')
        if len(lis) >= 5:
            item = {
                'product_code': lis[0].get_text(strip=True) if len(lis) > 0 else '',
                'move_code': lis[1].get_text(strip=True) if len(lis) > 1 else '',
                'quantity': lis[2].get_text(strip=True) if len(lis) > 2 else '',
                'price': lis[3].get_text(strip=True) if len(lis) > 3 else '',
                'total': lis[4].get_text(strip=True) if len(lis) > 4 else '',
            }
            cart_items.append(item)
            print(f"   - {item}")
    
    # 테이블 행 분석
    print("\n   테이블 행 분석:")
    for table in tables:
        rows = table.find_all('tr')
        for row in rows[:5]:
            cells = row.find_all(['td', 'th'])
            if cells:
                texts = [c.get_text(strip=True)[:20] for c in cells[:6]]
                print(f"   {texts}")
    
    # 3. 다른 API 시도
    print("\n3. 다른 장바구니 API 시도...")
    
    endpoints = [
        '/Home/GetCartList',
        '/Home/CartList',
        '/Order/GetCart',
        '/Order/CartList',
        '/Home/DataCart/list',
    ]
    
    for ep in endpoints:
        try:
            resp = session.post(f'https://gwn.geoweb.kr{ep}', timeout=5)
            if resp.status_code == 200 and len(resp.text) > 100:
                print(f"   ✓ {ep}: {len(resp.text)} bytes")
                print(f"     {resp.text[:100]}...")
        except:
            pass
    
    # 4. 장바구니 비우기
    print("\n4. 장바구니 비우기...")
    session.post('https://gwn.geoweb.kr/Home/DataCart/delAll')
    print("   완료")

if __name__ == "__main__":
    test()
