# -*- coding: utf-8 -*-
"""frmSave 폼과 주문 저장 로직 찾기"""

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

async def analyze():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        page = await browser.new_page()
        
        # 네트워크 요청 캡처
        requests_log = []
        def log_req(req):
            if req.method == 'POST':
                requests_log.append({'url': req.url, 'data': req.post_data})
        page.on('request', log_req)
        
        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')
        
        # 메인 페이지
        await page.goto('https://gwn.geoweb.kr/Home/Index')
        await page.wait_for_timeout(2000)
        
        # 페이지 HTML에서 frmSave 폼 찾기
        html = await page.content()
        
        print("="*60)
        print("frmSave 폼 찾기:")
        print("="*60)
        
        soup = BeautifulSoup(html, 'html.parser')
        
        # 모든 form 찾기
        forms = soup.find_all('form')
        for form in forms:
            form_id = form.get('id', '')
            form_action = form.get('action', '')
            print(f"폼: id={form_id}, action={form_action}")
            
            if 'save' in form_id.lower() or 'order' in form_id.lower():
                print(f"  >>> 주문 관련 폼 발견!")
                inputs = form.find_all('input')
                for inp in inputs[:10]:
                    print(f"    - {inp.get('name')}: {inp.get('value', '')[:30]}")
        
        # 주문저장 버튼 찾기
        print("\n" + "="*60)
        print("주문저장 버튼:")
        print("="*60)
        
        buttons = soup.find_all(['button', 'input'], type=['button', 'submit'])
        for btn in buttons:
            text = btn.get_text(strip=True) or btn.get('value', '')
            onclick = btn.get('onclick', '')
            if '저장' in text or '주문' in text:
                print(f"버튼: {text}")
                print(f"  onclick: {onclick[:100]}")
        
        # JavaScript에서 폼 action 찾기
        scripts = soup.find_all('script')
        for script in scripts:
            text = script.get_text() or ''
            if 'frmSave' in text:
                print("\n" + "="*60)
                print("frmSave 관련 스크립트:")
                print("="*60)
                # frmSave 근처 코드 출력
                idx = text.find('frmSave')
                print(text[max(0,idx-100):idx+300])
        
        await browser.close()

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