"""Sends only to loopback. No TradeOn requests or real purchases."""
import json
import sys
import time
from urllib.request import Request, urlopen
from merchant import sign

with open(sys.argv[1] if len(sys.argv) > 1 else 'webhooks.json') as source:
    fixture = json.load(source)
raw = fixture['raw'].encode()
assert sign(raw, fixture['timestamp'], fixture['secret']) == fixture['signature']
timestamp = str(int(time.time()))
request = Request('http://127.0.0.1:8080/webhooks/tradeon', method='POST', data=raw,
                  headers={'Content-Type': 'application/json', 'X-Timestamp': timestamp,
                           'X-Event-Id': json.loads(fixture['raw'])['event_id'], 'X-Event': json.loads(fixture['raw'])['event'],
                           'X-Signature': sign(raw, timestamp, fixture['secret'])})
with urlopen(request, timeout=5) as response:
    print({'status': response.status})  # First delivery and accepted duplicate: 204.
    assert response.status == 204
