# -*- coding: utf-8 -*-
"""AddCart 함수 전체 추출"""

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

async def extract():
    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'])
    
    resp = session.get('https://gwn.geoweb.kr/bundles/order?v=PGhSOAjQ9z6ruAJgJUFuhW9tGQSiJeX6ek-ky3E-tOk1')
    content = resp.text
    
    # AddCart 함수 전체 찾기
    # function AddCart(n,t,i){ ... }
    start = content.find('function AddCart')
    if start > 0:
        # 중괄호 매칭으로 함수 끝 찾기
        depth = 0
        end = start
        in_func = False
        
        for i in range(start, min(start + 5000, len(content))):
            if content[i] == '{':
                depth += 1
                in_func = True
            elif content[i] == '}':
                depth -= 1
                if in_func and depth == 0:
                    end = i + 1
                    break
        
        func_content = content[start:end]
        print("="*60)
        print("AddCart 함수 전체:")
        print("="*60)
        print(func_content)
        
        # ajax 호출 찾기
        ajax_match = re.search(r'\$\.ajax\s*\(\s*\{[^}]+\}', func_content, re.DOTALL)
        if ajax_match:
            print("\n" + "="*60)
            print("AJAX 호출:")
            print("="*60)
            print(ajax_match.group())
    
    # InsertOrder 함수도 찾기
    start2 = content.find('function InsertOrder')
    if start2 > 0:
        depth = 0
        end2 = start2
        in_func = False
        
        for i in range(start2, min(start2 + 3000, len(content))):
            if content[i] == '{':
                depth += 1
                in_func = True
            elif content[i] == '}':
                depth -= 1
                if in_func and depth == 0:
                    end2 = i + 1
                    break
        
        print("\n" + "="*60)
        print("InsertOrder 함수:")
        print("="*60)
        print(content[start2:end2][:1500])

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