# -*- coding: utf-8 -*-
"""지오영 JS 파일 다운로드 및 분석"""

import requests
import asyncio
from playwright.async_api import async_playwright
import re

async def download_and_analyze():
    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()
    
    # 세션 설정
    session = requests.Session()
    for c in cookies:
        session.cookies.set(c['name'], c['value'])
    
    # JS 파일 다운로드
    js_urls = [
        'https://gwn.geoweb.kr/bundles/order_product_cart?v=JPwFQ8DWaNMW1VmbtWYKTJqxT-5255z351W5iZE1qew1',
        'https://gwn.geoweb.kr/bundles/order?v=PGhSOAjQ9z6ruAJgJUFuhW9tGQSiJeX6ek-ky3E-tOk1'
    ]
    
    for url in js_urls:
        print(f"\n{'='*60}")
        print(f"분석: {url.split('/')[-1].split('?')[0]}")
        print('='*60)
        
        resp = session.get(url)
        content = resp.text
        
        # 장바구니/주문 관련 함수 찾기
        patterns = [
            (r'function\s+(fn\w*Cart\w*|add\w*Cart\w*|insert\w*Order\w*)\s*\([^)]*\)', 'function'),
            (r'(fn\w*Cart\w*|add\w*Cart\w*)\s*=\s*function', 'var function'),
            (r'url\s*:\s*["\']([^"\']*(?:Cart|Order|Add)[^"\']*)["\']', 'ajax url'),
            (r'\$\.(?:ajax|post|get)\s*\(\s*["\']([^"\']+)["\']', 'ajax call'),
        ]
        
        found = {}
        for pattern, name in patterns:
            matches = re.findall(pattern, content, re.IGNORECASE)
            if matches:
                for m in matches:
                    if m not in found:
                        found[m] = name
        
        for item, ptype in found.items():
            print(f"[{ptype}] {item}")
        
        # InsertOrder 함수 찾기
        if 'InsertOrder' in content or 'insertOrder' in content:
            print("\n--- InsertOrder 함수 발견! ---")
            # 해당 부분 추출
            idx = content.lower().find('insertorder')
            if idx > 0:
                snippet = content[max(0, idx-100):idx+500]
                print(snippet[:600])
        
        # AddCart 패턴 찾기
        add_patterns = re.findall(r'.{50}AddCart.{100}|.{50}addCart.{100}', content, re.IGNORECASE)
        if add_patterns:
            print("\n--- AddCart 관련 ---")
            for p in add_patterns[:3]:
                print(p)
        
        # ajax 호출 상세
        ajax_pattern = r'\$\.ajax\s*\(\s*\{[^}]{50,500}(Cart|Order)[^}]{0,200}\}'
        ajax_matches = re.findall(ajax_pattern, content, re.IGNORECASE | re.DOTALL)
        if ajax_matches:
            print(f"\n--- AJAX 호출 {len(ajax_matches)}개 발견 ---")

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