# -*- coding: utf-8 -*-
"""지오영 장바구니 API 직접 테스트 (requests)"""

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

async def get_cookies():
    """Playwright로 로그인 후 쿠키 획득"""
    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_cart_api():
    # 1. 쿠키 획득
    print("1. 로그인 중...")
    cookies = asyncio.run(get_cookies())
    
    # 2. requests 세션 설정
    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',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'X-Requested-With': 'XMLHttpRequest'
    })
    
    print(f"   쿠키: {[c['name'] for c in cookies]}")
    
    # 3. 제품 검색
    print("\n2. 제품 검색...")
    search_resp = session.post('https://gwn.geoweb.kr/Home/PartialSearchProduct', data={
        'srchText': '643104281',
        'srchCate': '',
        'prdtType': '',
        'prdOrder': '',
        'srchCompany': '',
        'startdate': '',
        'enddate': ''
    })
    print(f"   검색 응답: {search_resp.status_code}, 길이: {len(search_resp.text)}")
    
    # 4. 장바구니 API 테스트 - 여러 엔드포인트 시도
    print("\n3. 장바구니 API 테스트...")
    
    endpoints = [
        '/Home/PartialProductCart',
        '/Home/AddCart',
        '/Order/AddCart',
        '/Home/AddToCart',
        '/Order/AddToCart',
        '/Home/InsertCart',
        '/Order/InsertCart',
    ]
    
    for endpoint in endpoints:
        url = f'https://gwn.geoweb.kr{endpoint}'
        
        # 다양한 파라미터 조합 시도
        params_list = [
            {'prdtCode': '643104281', 'qty': 1},
            {'productCode': '643104281', 'quantity': 1},
            {'code': '643104281', 'cnt': 1},
            {'insCode': '643104281', 'orderQty': 1},
        ]
        
        for params in params_list:
            try:
                resp = session.post(url, data=params, timeout=5)
                if resp.status_code == 200:
                    text = resp.text[:200]
                    if 'error' not in text.lower() and '404' not in text:
                        print(f"   ✓ {endpoint}")
                        print(f"     Params: {params}")
                        print(f"     Response: {text[:100]}...")
            except Exception as e:
                pass
    
    # 5. 현재 장바구니 조회
    print("\n4. 장바구니 조회...")
    cart_resp = session.post('https://gwn.geoweb.kr/Home/PartialProductCart')
    print(f"   응답: {cart_resp.status_code}")
    
    soup = BeautifulSoup(cart_resp.text, 'html.parser')
    
    # 장바구니 테이블에서 상품 찾기
    rows = soup.find_all('tr')
    print(f"   테이블 행: {len(rows)}개")
    
    # HTML에서 장바구니 추가 폼 찾기
    forms = soup.find_all('form')
    for form in forms:
        action = form.get('action', '')
        if 'cart' in action.lower() or 'order' in action.lower():
            print(f"   폼 발견: {action}")
            inputs = form.find_all('input')
            for inp in inputs:
                print(f"     - {inp.get('name')}: {inp.get('value', '')}")

if __name__ == "__main__":
    test_cart_api()
