import urllib.request, json

data = json.dumps({'email':'testplan@test.ru','password':'test123'}).encode()
req = urllib.request.Request('http://localhost:8000/api/login', data=data, headers={'Content-Type':'application/json'}, method='POST')
r = json.loads(urllib.request.urlopen(req).read())
token = r['access_token']
print('1. Login OK')

# Upload via multipart
boundary = '----TestBoundary123'
body_parts = []
body_parts.append('--' + boundary)
body_parts.append('Content-Disposition: form-data; name="file"; filename="test.json"')
body_parts.append('Content-Type: application/json')
body_parts.append('')
body_parts.append(json.dumps([{'ticket_id':'T-002','category':'network','description':'Network down','client':'Petr','messages':[{'role':'client','text':'internet not working'},{'role':'support','text':'try rebooting the router'}]}]))
body_parts.append('--' + boundary + '--')
body_parts.append('')
body = '\r\n'.join(body_parts).encode()

headers = {
    'Content-Type': 'multipart/form-data; boundary=' + boundary,
    'Authorization': 'Bearer ' + token,
}
req = urllib.request.Request('http://localhost:8000/api/collections/9756bf5f-a89d-424d-bd73-ff4ad839ae4b/tickets/upload', data=body, headers=headers, method='POST')
try:
    resp = json.loads(urllib.request.urlopen(req).read().decode())
    print('2. Upload OK:', resp)
except urllib.error.HTTPError as e:
    print('2. Upload error:', e.code, e.read().decode())
