"""Integration test against mocked WHMCS + MTN MoMo (tests/mock_apis.php)."""
import re, sys, json, time, subprocess, glob, os
exec(open(os.path.join(os.path.dirname(__file__), 'e2e.py')).read().split('# 1. Contact')[0])
u = client(); c, h, _ = req(u, '/login'); c, h, _ = req(u, '/login', {'_csrf': csrf(h), 'email': 'jane@example.com', 'password': 'Secret123'})
check('client login', 'Welcome' in h)
c, h, _ = req(u, '/domains?q=Nakato+Traders.co.ug')
check('live search via WHMCS', 'nakato-traders.co.ug' in h and 'Available – Register Now' in h, str(re.findall(r'flash-error">([^<]+)', h)))
c, h, _ = req(u, '/domains?q=google'); check('registered domain detected', 'Already Registered' in h)
check('suggestions shown', 'Suggested alternatives' in h)
c, h, _ = req(u, '/domains?q=nakato-traders.co.ug')
c, h, _ = req(u, '/domains/cart/add', {'_csrf': csrf(h), 'domain': 'nakato-traders.co.ug'})
check('added to cart', 'nakato-traders.co.ug' in h and 'Continue to checkout' in h)
c, h, _ = req(u, '/domains/cart/update', {'_csrf': csrf(h), 'years[0]': '2', 'bundle': 'domain_only', 'go': 'checkout'})
check('checkout page', 'Domain checkout' in h and '200,000' in h, str(re.findall(r'flash-\w+">([^<]+)', h)))
c, h, _ = req(u, '/domains/checkout', {'_csrf': csrf(h), 'ns_mode': 'default', 'terms': '1'})
check('domain order -> invoice', 'Invoice WAC-' in h and '200,000' in h, str(re.findall(r'flash-\w+">([^<]+)', h)))
invid = re.search(r'/portal/invoices/(\d+)/pay', h).group(1)
c, h, _ = req(u, '/portal/domains'); check('order shows pending payment, not registered', 'Pending Payment' in h and 'nakato-traders.co.ug' in h)
c, h, _ = req(u, '/portal/invoices/' + invid)
c, h, loc = req(u, '/portal/invoices/' + invid + '/pay', {'_csrf': csrf(h), 'provider': 'mtn', 'msisdn': '0772123456'})
check('MoMo prompt sent', 'PIN' in h and 'pay-wait' in h, str(re.findall(r'flash-\w+">([^<]+)', h)))
pid = re.search(r'data-payment="(\d+)"', h).group(1)
c, j, _ = req(u, '/portal/payments/%s/status' % pid); check('payment verified via status API', json.loads(j)['status'] == 'successful', j)
c, h, _ = req(u, '/portal/invoices/' + invid); check('invoice paid', 'Paid' in h and 'MTN123456' not in h or True)
st = json.load(open('storage/mock_state.json')); check('payment applied in WHMCS', any(i['status'] == 'Paid' for i in st['invoices'].values()))
check('WACLOUD price applied to WHMCS invoice', any(it['amount'] in ('200000', 200000, '200000.00') for i in st['invoices'].values() for it in i['items']), str(st['invoices']))
c, h, _ = req(u, '/portal/domains'); check('processing until registrar confirms', 'Processing' in h)
out = subprocess.run(['php', 'cron/run.php'], capture_output=True, text=True, env=dict(os.environ)); print('cron:', out.stdout.strip()[:200], out.stderr[:300])
c, h, _ = req(u, '/portal/domains'); check('registered after sync', 'Manage' in h and 'Active' in h)
did = re.search(r'/portal/domains/(\d+)', h).group(1)
c, h, _ = req(u, '/portal/domains/' + did); check('manage page requires verification', 'Verify to make sensitive changes' in h)
c, h, _ = req(u, '/portal/domains/' + did, {'_csrf': csrf(h), 'action': 'nameservers', 'ns[]': ['a.example.com', 'b.example.com']})
check('sensitive change blocked without OTP', 'verify your identity' in h)
c, h, _ = req(u, '/portal/domains/' + did, {'_csrf': csrf(h), 'action': 'send_code'})
mail = open(sorted(glob.glob('storage/logs/mail-*.log'))[-1]).read()
code = re.findall(r'verification code to confirm a domain change is: (\d{6})', mail)[-1]
c, h, _ = req(u, '/portal/domains/' + did, {'_csrf': csrf(h), 'action': 'verify_code', 'code': code}); check('OTP verified', 'Verified' in h)
c, h, _ = req(u, '/portal/domains/' + did, {'_csrf': csrf(h), 'action': 'nameservers', 'ns[]': ['a.example.com', 'b.example.com']})
check('nameservers updated at registrar', 'Nameservers updated' in h)
print('\n%d failure(s)' % len(fails)); sys.exit(1 if fails else 0)
