"""End-to-end smoke test against the PHP dev server (SQLite). Run: python3 tests/e2e.py"""
import re, sys, time, urllib.request, urllib.parse, http.cookiejar, json
BASE = 'http://127.0.0.1:8099'
fails = []
def client():
    cj = http.cookiejar.CookieJar()
    class NoRedir(urllib.request.HTTPRedirectHandler):
        def redirect_request(self, *a, **k): return None
    op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj), NoRedir)
    return op
def req(op, path, data=None, follow=True):
    body = urllib.parse.urlencode(data, doseq=True).encode() if data is not None else None
    r = urllib.request.Request(BASE + path, data=body)
    try:
        resp = op.open(r); code, html, loc = resp.status, resp.read().decode(), None
    except urllib.error.HTTPError as e:
        code, html, loc = e.code, e.read().decode(errors='ignore'), e.headers.get('Location')
    if follow and code in (301, 302) and loc:
        return req(op, loc if loc.startswith('/') else urllib.parse.urlparse(loc).path + ('?' + urllib.parse.urlparse(loc).query if urllib.parse.urlparse(loc).query else ''))
    return code, html, loc
def csrf(html): return re.search(r'name="_csrf" value="([a-f0-9]+)"', html).group(1)
def captcha(html):
    m = re.search(r'what is (\d+) \+ (\d+)', html); return str(int(m.group(1)) + int(m.group(2))) if m else ''
def check(name, cond, extra=''):
    print(('PASS ' if cond else 'FAIL ') + name + (' ' + extra if extra and not cond else ''))
    if not cond: fails.append(name)
def flash(html):
    return re.findall(r'class="flash flash-\w+"[^>]*>([^<]+)', html)

# 1. Contact enquiry -> lead
g = client(); c, h, _ = req(g, '/contact')
form = {'_csrf': csrf(h), 'name': 'Jane Nakato', 'organisation': 'Nakato Traders', 'email': 'jane@example.com', 'phone': '+256772123456', 'org_type': 'Retailer / distributor', 'contact_method': 'WhatsApp',
        'service_interest': 'Custom ERP development', 'message': 'Need stock control for 3 branches', 'consent': '1', '_ts': str(int(time.time()) - 10), 'captcha': captcha(h)}
c, h, _ = req(g, '/contact', form)
check('enquiry submits & shows reference', 'reference number is' in h, str(flash(h)))
# invalid form
c, h, _ = req(g, '/contact'); bad = dict(form, _csrf=csrf(h), email='bad', captcha=captcha(h))
c, h, _ = req(g, '/contact', bad); check('enquiry validation rejects bad email', 'valid email' in h)
# honeypot
c, h, _ = req(g, '/contact'); c, h, _ = req(g, '/contact', dict(form, _csrf=csrf(h), captcha=captcha(h), website_url='spam'))
check('honeypot blocks bot', 'Security check failed' in h)

# 2. Specialised request (ERP quote with modules)
c, h, _ = req(g, '/request?type=erp_quote')
c, h, _ = req(g, '/request', {'_csrf': csrf(h), 'type': 'erp_quote', 'name': 'Dr Okello', 'email': 'okello@clinic.ug', 'phone': '0701234567', 'erp_solution': 'Hospital & Clinic Management', 'users': '20', 'modules[]': ['Pharmacy', 'Finance and accounting'], 'consent': '1', '_ts': str(int(time.time()) - 10), 'captcha': captcha(h)})
check('ERP quote request creates lead', 'reference number is' in h, str(flash(h)))

# 3. Solution finder
c, h, _ = req(g, '/solution-finder')
c, h, _ = req(g, '/solution-finder', {'_csrf': csrf(h), 'org_type': 'School / educational institution', 'size': '51-200', 'ops': 'paper', 'presence': 'social', 'needs[]': ['website', 'erp', 'ai'], 'budget': 'growth', 'timeline': 'Within 3 months'})
check('solution finder recommends packages', 'Recommended packages' in h and 'School Management System' in h)

# 4. Booking
c, d, _ = req(g, '/api/available-days'); days = json.loads(d)['days']
check('availability has open days', len(days) > 0)
c, s, _ = req(g, '/api/slots?date=' + days[0]); slots = json.loads(s)['slots']
c, h, _ = req(g, '/book-consultation')
c, h, loc = req(g, '/book-consultation', {'_csrf': csrf(h), 'meeting_type': 'erp_demo', 'service': 'School Management System', 'name': 'Peter Ssemwogerere', 'email': 'peter@school.ug', 'phone': '+256752000111', 'slot': slots[0]['start'],
    'challenge': 'Manual fees collection', 'consent': '1', '_ts': str(int(time.time()) - 10), 'captcha': captcha(h)})
check('booking confirmed with meeting link', 'Your meeting is booked' in h and 'meet.jit.si' in h, str(flash(h)) + str(re.findall(r'field-error">([^<]+)', h)) + str(c))
m = re.search(r'/booking/manage/([a-f0-9]+)', h); token = m.group(1) if m else ''
c, h, _ = req(g, '/booking/manage/' + token); check('booking manage page', 'Manage your meeting' in h)

# 5. Register, order, pay by bank transfer
u = client(); c, h, _ = req(u, '/order/business-growth')
c, h, loc = req(u, '/order/business-growth', {'_csrf': csrf(h), 'currency': 'UGX', 'cycle': 'monthly', 'domain': 'nakato.co.ug', 'terms': '1'}, follow=False)
check('guest order redirects to register', loc and loc.endswith('/register'))
c, h, _ = req(u, '/register')
c, h, _ = req(u, '/register', {'_csrf': csrf(h), 'name': 'Jane Nakato', 'organisation': 'Nakato Traders', 'email': 'jane@example.com', 'phone': '+256772123456', 'currency': 'UGX', 'password': 'Secret123', 'password_confirm': 'Secret123', 'consent': '1', '_ts': str(int(time.time()) - 10), 'captcha': captcha(h)})
check('registration resumes order to invoice', 'Invoice WAC-' in h, str(flash(h)))
inv = re.search(r'/portal/invoices/(\d+)', h) or re.search(r'Invoice (WAC-\d{4}-\d+)', h)
c, h, _ = req(u, '/portal/invoices'); invid = re.search(r'/portal/invoices/(\d+)"', h).group(1)
c, h, _ = req(u, '/portal/invoices/' + invid)
check('invoice shows setup + recurring', '2,500,000' in h and '450,000' in h and '2,950,000' in h)
c, h, _ = req(u, '/portal/invoices/' + invid + '/pay', {'_csrf': csrf(h), 'provider': 'bank', 'bank_ref': 'STANBIC-TRX-889'})
check('bank payment pending (not auto-paid)', 'Finance will verify' in h and 'Unpaid' in h, str(flash(h)))
c, h, _ = req(u, '/portal/services'); check('subscription pending before verification', 'Pending' in h)

# 6. Admin verifies bank transfer -> paid, subscription active, project created
a = client(); c, h, _ = req(a, '/login'); c, h, _ = req(a, '/login', {'_csrf': csrf(h), 'email': 'admin@waclouds.com', 'password': 'AdminPass123!'})
check('admin login', 'Dashboard' in h or 'Good ' in h)
c, h, _ = req(a, '/admin/invoices/' + invid); pid = re.search(r'name="payment_id" value="(\d+)"', h).group(1)
c, h, _ = req(a, '/admin/invoices/' + invid, {'_csrf': csrf(h), 'payment_id': pid, 'action': 'verify_bank', 'bank_ref': 'STANBIC-TRX-889'})
check('verification requires statement confirmation', 'Confirm you have matched' in h)
c, h, _ = req(a, '/admin/invoices/' + invid, {'_csrf': csrf(h), 'payment_id': pid, 'action': 'verify_bank', 'bank_ref': 'STANBIC-TRX-889', 'confirm_statement': '1'})
check('invoice marked paid after verification', 'Paid' in h, str(flash(h)))
c, h, _ = req(u, '/portal/services'); check('subscription active', 'Active' in h)
c, h, _ = req(u, '/portal/projects'); check('delivery project auto-created', 'Business Growth' in h)
c, h, _ = req(u, '/portal/websites'); check('website record created for tracker', 'nakato.co.ug' in h)
c, h, _ = req(u, '/portal/invoices/' + invid + '/receipt'); check('receipt available', 'RECEIPT' in h and 'PAID' in h)

# 7. Upgrade flow
c, h, _ = req(u, '/portal/services'); sid = re.search(r'/portal/services/(\d+)', h).group(1)
c, h, _ = req(u, '/portal/services/' + sid)
check('upgrade options listed', 'Enterprise Digital' in h)
epid = re.search(r'<option value="(\d+)">Enterprise Digital', h).group(1)
c, h, _ = req(u, '/portal/services/' + sid, {'_csrf': csrf(h), 'action': 'change', 'package_id': epid})
check('upgrade creates prorated invoice', 'Upgrade' in h and 'prorated' in h, str(flash(h)))

# 8. Coupon
c, h, _ = req(a, '/admin/content/coupons/new')
c, h, _ = req(a, '/admin/content/coupons/new', {'_csrf': csrf(h), 'code': 'launch10', 'type': 'percent', 'value': '10', 'applies_to': 'both', 'is_active': '1'})
c, h, _ = req(u, '/order/seo-starter')
c, cj, _ = req(u, '/api/coupon', {'_csrf': csrf(h), 'code': 'LAUNCH10', 'package_id': re.search(r'data-package="(\d+)"', h).group(1), 'cycle': 'monthly', 'currency': 'UGX'})
check('coupon validates', json.loads(cj).get('ok') is True, cj)

# 9. Support ticket + staff reply
c, h, _ = req(u, '/portal/tickets/new')
c, h, _ = req(u, '/portal/tickets', {'_csrf': csrf(h), 'category': 'Website maintenance', 'priority': 'high', 'subject': 'Contact form not sending', 'body': 'Please check'})
check('ticket created', 'Contact form not sending' in h)
tid = re.search(r'TKT-\d+-\w+', h)
c, h, _ = req(a, '/admin/tickets'); atid = re.search(r'/admin/tickets/(\d+)', h).group(1)
c, h, _ = req(a, '/admin/tickets/' + atid); c, h, _ = req(a, '/admin/tickets/' + atid, {'_csrf': csrf(h), 'body': 'Fixed — SMTP updated.', 'status': 'answered'})
c, h, _ = req(u, '/portal/tickets/' + atid); check('customer sees staff reply', 'Fixed — SMTP updated.' in h)

# 10. CRM: lead pipeline & conversion
c, h, _ = req(a, '/admin/leads'); check('leads listed', 'Nakato Traders' in h and 'Okello' in h)
lid = re.search(r'/admin/leads/(\d+)">ENQ', h).group(1)
c, h, _ = req(a, '/admin/leads/' + lid); c, h, _ = req(a, '/admin/leads/' + lid, {'_csrf': csrf(h), 'action': 'status', 'status': 'proposal_submitted'})
check('lead status updated', 'Proposal Submitted' in h)

# 11. Project milestone approval by client
c, h, _ = req(a, '/admin/projects'); prid = re.search(r'/admin/projects/(\d+)', h).group(1)
c, h, _ = req(a, '/admin/projects/' + prid)
mids = list(dict.fromkeys(re.findall(r'name="milestone_id" value="(\d+)"', h)))
for mid in mids[:4]:
    c, h, _ = req(a, '/admin/projects/' + prid, {'_csrf': csrf(h), 'action': 'milestone_update', 'milestone_id': mid, 'status': 'done'})
c, h, _ = req(u, '/portal/projects/' + prid); check('client sees approval request', 'Approve' in h)
mid = re.search(r'name="milestone_id" value="(\d+)"', h).group(1)
c, h, _ = req(u, '/portal/projects/' + prid, {'_csrf': csrf(h), 'milestone_id': mid, 'action': 'approve', 'note': 'Looks great'})
check('client approves milestone', 'milestone approved' in h, str(flash(h)))

# 12. Admin pages render
for p in ['/admin', '/admin/customers', '/admin/subscriptions', '/admin/invoices', '/admin/payments', '/admin/packages', '/admin/packages/1', '/admin/packages/new', '/admin/bookings', '/admin/projects', '/admin/websites', '/admin/tickets', '/admin/training', '/admin/domains', '/admin/whmcs',
          '/admin/reports', '/admin/communications', '/admin/users', '/admin/settings', '/admin/audit', '/admin/system', '/admin/content/categories', '/admin/content/articles/new', '/admin/content/tlds', '/admin/content/templates', '/admin/content/episodes/new', '/admin/leads/new']:
    c, h, _ = req(a, p); check('admin ' + p, c == 200 and 'Fatal' not in h and 'Warning' not in h, str(c))
# 13. Portal pages
for p in ['/portal', '/portal/services', '/portal/domains', '/portal/websites', '/portal/projects', '/portal/invoices', '/portal/tickets', '/portal/meetings', '/portal/training', '/portal/profile']:
    c, h, _ = req(u, p); check('portal ' + p, c == 200 and 'Fatal' not in h and 'Warning' not in h, str(c))
# 14. Access control: client cannot reach admin; other client cannot see invoice
c, h, _ = req(u, '/admin/invoices'); check('client blocked from admin', c == 403)
o = client(); c, h, _ = req(o, '/register')
req(o, '/register', {'_csrf': csrf(h), 'name': 'Other', 'email': 'other@example.com', 'phone': '+256772999999', 'password': 'Secret123', 'password_confirm': 'Secret123', 'consent': '1', '_ts': str(int(time.time()) - 10), 'captcha': captcha(h)})
c, h, _ = req(o, '/portal/invoices/' + invid); check('other client cannot view invoice (IDOR)', c == 404)
# 15. CSRF enforced
c, h, _ = req(u, '/portal/profile', {'name': 'x'}); check('CSRF enforced', c == 419)
# 16. Training cohort
c, h, _ = req(a, '/admin/training'); progid = re.search(r'<option value="(\d+)">AI Awareness', h).group(1)
c, h, _ = req(a, '/admin/training', {'_csrf': csrf(h), 'programme_id': progid, 'client_org': 'Stanbic Uganda', 'mode': 'onsite', 'start_date': '2026-12-01', 'end_date': '2026-12-02'})
c, h, _ = req(a, urllib.parse.urlparse(BASE + '/admin/training').path)
cid = re.search(r'/admin/training/(\d+)', h).group(1); c, h, _ = req(a, '/admin/training/' + cid)
c, h, _ = req(a, '/admin/training/' + cid, {'_csrf': csrf(h), 'action': 'participants', 'bulk': 'Alice A, alice@x.com, Finance\nBob B, bob@x.com, HR'})
check('participants added', 'Alice A' in h)
c, h, _ = req(a, '/admin/training/' + cid + '?report=1'); check('completion report', 'Completion Report' in h)
print('\n%d failure(s)' % len(fails)); sys.exit(1 if fails else 0)
