# -*- coding: utf-8 -*-
import sys; sys.path.insert(0, '.'); import wholesale_path
from wholesale import SooinSession
from bs4 import BeautifulSoup
import re

s = SooinSession()
s.login()
s.clear_cart()

result = s.search_products('코자정')
product = result['items'][0]
s.add_to_cart(product['internal_code'], qty=1, price=product['price'], stock=product['stock'])

resp = s.session.get(f'{s.BAG_VIEW_URL}?currVenCd={s.vendor_code}', timeout=15)
soup = BeautifulSoup(resp.content, 'html.parser')
form = soup.find('form', {'id': 'frmBag'})

# form action 확인
form_action = form.get('action', '')
print(f'form action: {form_action}')

# 올바른 URL 구성
ORDER_END_URL = 'http://sooinpharm.co.kr/Service/Order/OrderEnd.asp'

form_data = {}
for inp in form.find_all('input'):
    name = inp.get('name', '')
    if not name: continue
    inp_type = inp.get('type', '').lower()
    if inp_type == 'checkbox':
        form_data[name] = 'on'  # 체크박스 선택
    else:
        form_data[name] = inp.get('value', '')

# x, y 좌표 (image input 클릭)
form_data['x'] = '10'
form_data['y'] = '10'

print(f"chk_0: {form_data.get('chk_0')}")
print(f"kind: {form_data.get('kind')}")

print(f'\nPOST to: {ORDER_END_URL}')
resp = s.session.post(
    ORDER_END_URL,
    data=form_data,
    headers={
        'Content-Type': 'application/x-www-form-urlencoded',
        'Referer': f'{s.BAG_VIEW_URL}?currVenCd={s.vendor_code}'
    },
    timeout=30
)

print(f'응답 상태: {resp.status_code}')
print(f'응답 길이: {len(resp.text)}')

# alert 확인
alert_match = re.search(r'alert\("([^"]*)"\)', resp.text)
alert_msg = alert_match.group(1) if alert_match else 'N/A'
print(f'alert 메시지: "{alert_msg}"')

# 응답 일부 출력
print('\n응답 앞부분:')
print(resp.text[:1000])

# 장바구니 확인
resp2 = s.session.get(f'{s.BAG_VIEW_URL}?currVenCd={s.vendor_code}', timeout=15)
soup2 = BeautifulSoup(resp2.content, 'html.parser')
int_array = soup2.find('input', {'name': 'intArray'})
val = int_array.get('value') if int_array else '없음'
print(f'\n주문 후 intArray: {val}')

if val == '-1':
    print('\n🎉 주문 성공!')
else:
    print('\n❌ 주문 실패')
