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

s = SooinSession()
print('1. 준비...')
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_data = {}
for inp in form.find_all('input'):
    name = inp.get('name', '')
    if not name:
        continue
    inp_type = inp.get('type', 'text').lower()
    if inp_type == 'checkbox':
        continue
    form_data[name] = inp.get('value', '')

form_data['kind'] = 'order'
form_data['tx_memo'] = '좌표 테스트'

# x, y 좌표 추가!
form_data['x'] = '10'
form_data['y'] = '10'

print(f"   intArray: {form_data.get('intArray')}")
print(f"   x, y 추가: {form_data.get('x')}, {form_data.get('y')}")

print('\n2. POST...')
resp = s.session.post(
    s.BAG_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"   응답 길이: {len(resp.text)}")

# alert 내용 확인
import re
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('\n3. 주문 후 장바구니...')
resp2 = s.session.get(f'{s.BAG_VIEW_URL}?currVenCd={s.vendor_code}', timeout=15)
soup2 = BeautifulSoup(resp2.content, 'html.parser')
int_array2 = soup2.find('input', {'name': 'intArray'})
print(f"   intArray: {int_array2.get('value')}")

if int_array2.get('value') == '-1':
    print('\n🎉 주문 성공!')
