#!/usr/bin/env bash
set -euo pipefail
python3 - "$@" <<'PY'
import json, os, sys, uuid, time
from pathlib import Path
import urllib.request
if len(sys.argv) != 2 or sys.argv[1] not in ('staging', 'production'):
    raise SystemExit('Expected staging or production')
if os.environ['VERIFY_ENVIRONMENT'] != sys.argv[1]:
    raise SystemExit('Agent environment mismatch')
base = os.environ['VERIFY_BASE_URL'].rstrip('/')
if not base.startswith('https://'):
    raise SystemExit('HTTPS required')
token = Path(os.environ['VERIFY_TOKEN_FILE']).read_text().strip()
payload = json.loads(Path(os.environ['VERIFY_PAYLOAD_FILE']).read_text())
if payload.get('tenant') != os.environ['VERIFY_TENANT'] or payload.get('synthetic') is not True:
    raise SystemExit('Only the approved synthetic tenant fixture is allowed')
key = 'jenkins-' + str(uuid.uuid4())
class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None
opener = urllib.request.build_opener(NoRedirect)
def request(method, path, data=None):
    req = urllib.request.Request(base + path,
        data=None if data is None else json.dumps(data).encode(), method=method,
        headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json', 'Idempotency-Key': key})
    with opener.open(req, timeout=20) as response:
        return json.load(response)
first = request('POST', '/orders', payload)
second = request('POST', '/orders', payload)
identifier = str(first['id'])
if not identifier or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' for c in identifier):
    raise SystemExit('Unexpected order identifier')
if str(second['id']) != identifier:
    raise SystemExit('Idempotency check failed')
order = request('GET', '/orders/' + identifier)
if str(order['id']) != identifier or order['tenant'] != payload['tenant'] or order['status'] not in ('created', 'accepted', 'completed'):
    raise SystemExit('Order persistence/business state check failed')
if os.environ.get('VERIFY_ASYNC') == 'true':
    for _ in range(60):
        order = request('GET', '/orders/' + identifier)
        if order['status'] == 'completed':
            break
        time.sleep(1)
    else:
        raise SystemExit('Async completion timeout')
    if order['ledger_amount_cents'] != payload['amount_cents'] or order['projection']['amount_cents'] != payload['amount_cents']:
        raise SystemExit('Ledger/projection reconciliation failed')
print('Business verification passed: create, idempotency, persistence and configured async checks')
PY
