# -*- coding: utf-8 -*-
"""주문 확정 API 찾기"""

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

async def find_order_api():
    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'])
    
    # order.js 다운로드
    resp = session.get('https://gwn.geoweb.kr/bundles/order?v=PGhSOAjQ9z6ruAJgJUFuhW9tGQSiJeX6ek-ky3E-tOk1')
    content = resp.text
    
    # InsertOrder, ConfirmOrder, SubmitOrder 등 찾기
    print("="*60)
    print("주문 관련 함수 찾기")
    print("="*60)
    
    # 함수 찾기
    funcs = ['InsertOrder', 'ConfirmOrder', 'SubmitOrder', 'SaveOrder', 'ProcessOrder', 'DataOrder']
    for func in funcs:
        start = content.find(f'function {func}')
        if start < 0:
            start = content.find(f'{func}=function')
        if start < 0:
            start = content.find(f'{func}(')
        
        if start > 0:
            print(f"\n{func} 발견!")
            # 함수 내용 출력
            snippet = content[max(0, start-20):start+800]
            print(snippet[:600])
    
    # DataOrder URL 찾기
    print("\n" + "="*60)
    print("DataOrder 관련")
    print("="*60)
    
    dataorder_pattern = re.findall(r'.{30}DataOrder.{100}', content)
    for p in dataorder_pattern[:5]:
        print(p)
    
    # 모든 ajax URL 찾기
    print("\n" + "="*60)
    print("주문 관련 URL")
    print("="*60)
    
    urls = re.findall(r'url\s*:\s*["\']([^"\']*(?:Order|Submit|Confirm|Save)[^"\']*)["\']', content, re.IGNORECASE)
    for url in set(urls):
        print(url)

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