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

import asyncio
from playwright.async_api import async_playwright
import json

async def capture_cart_api():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        page = await browser.new_page()
        
        # 요청/응답 캡처
        cart_requests = []
        
        async def handle_request(request):
            if 'Cart' in request.url or 'Order' in request.url or 'Add' in request.url:
                cart_requests.append({
                    'url': request.url,
                    'method': request.method,
                    'headers': dict(request.headers),
                    'data': request.post_data
                })
        
        page.on('request', handle_request)
        
        # 로그인
        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')
        print("로그인 완료")
        
        # 쿠키 저장
        cookies = await page.context.cookies()
        print(f"쿠키: {[c['name'] for c in cookies]}")
        
        # 검색 페이지
        await page.goto('https://gwn.geoweb.kr/Home/Index')
        await page.wait_for_timeout(2000)
        
        # 검색 (AJAX)
        await page.evaluate('''
            $.ajax({
                url: "/Home/PartialSearchProduct",
                type: "POST",
                data: {srchText: "643104281"},
                success: function(data) {
                    console.log("검색 결과:", data.substring(0, 500));
                }
            });
        ''')
        await page.wait_for_timeout(2000)
        
        # 장바구니 추가 시도 (JavaScript로)
        result = await page.evaluate('''
            async function testCart() {
                // 장바구니 추가 함수 찾기
                if (typeof AddCart !== 'undefined') {
                    return "AddCart 함수 존재";
                }
                if (typeof fnAddCart !== 'undefined') {
                    return "fnAddCart 함수 존재";
                }
                
                // 전역 함수 목록
                var funcs = [];
                for (var key in window) {
                    if (typeof window[key] === 'function' && 
                        (key.toLowerCase().includes('cart') || 
                         key.toLowerCase().includes('order') ||
                         key.toLowerCase().includes('add'))) {
                        funcs.push(key);
                    }
                }
                return "발견된 함수: " + funcs.join(", ");
            }
            return testCart();
        ''')
        print(f"JavaScript 분석: {result}")
        
        # 페이지 소스에서 장바구니 관련 스크립트 찾기
        scripts = await page.evaluate('''
            var scripts = document.querySelectorAll('script');
            var result = [];
            scripts.forEach(function(s) {
                var text = s.textContent || s.innerText || '';
                if (text.includes('Cart') || text.includes('AddProduct')) {
                    result.push(text.substring(0, 1000));
                }
            });
            return result;
        ''')
        
        await browser.close()
        
        print("\n" + "="*60)
        print("캡처된 Cart/Order 요청:")
        print("="*60)
        for r in cart_requests:
            print(json.dumps(r, indent=2, ensure_ascii=False))
        
        print("\n" + "="*60)
        print("장바구니 관련 스크립트:")
        print("="*60)
        for i, s in enumerate(scripts[:3]):
            print(f"\n--- Script {i+1} ---")
            print(s[:800])

if __name__ == "__main__":
    asyncio.run(capture_cart_api())
