# Smoke test (needs config env=dev, a super admin superadmin@example.com / Admin#2026x, and pip install requests)
import requests, re, time, sys
import os
B = os.environ.get('CSSD_URL', 'http://localhost:8080')
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
LOG = ROOT + '/storage/logs/otp.log'
ok = 0; bad = 0
def check(cond, msg):
    global ok, bad
    if cond: ok += 1; print('  ✓', msg)
    else: bad += 1; print('  ✗', msg)
def csrf(html):
    m = re.search(r'name="_csrf" value="([0-9a-f]+)"', html); return m.group(1) if m else ''
def last_otp():
    return open(LOG).read().strip().splitlines()[-1].split()[-1]
def get(s, p): return s.get(B + p, allow_redirects=True)
def post(s, p, data, page=None):
    h = get(s, page or p).text
    data = dict(data); data['_csrf'] = csrf(h)
    return s.post(B + p, data=data, allow_redirects=True)

import subprocess
subprocess.run(['mysql', '-uroot', '-e', "DROP DATABASE IF EXISTS cssd_shiva; DELETE FROM cssd_control.tenants WHERE client_code='SHIVA'; DELETE FROM cssd_control.leads; DELETE FROM cssd_control.login_attempts;"])
print('Level 1')
L1 = requests.Session()
r = post(L1, '/admin/login', {'email': 'superadmin@example.com', 'password': 'wrong'})
check('incorrect' in r.text, 'wrong password rejected')
r = post(L1, '/admin/login', {'email': 'superadmin@example.com', 'password': 'Admin#2026x'})
check('/admin/otp' in r.url and 'Check your email' in r.text, 'OTP step shown')
r = post(L1, '/admin/otp', {'code': '000000'})
check('Wrong code' in r.text, 'wrong OTP rejected')
r = post(L1, '/admin/otp', {'code': last_otp()})
check('Platform dashboard' in r.text, 'L1 dashboard after OTP')
r = post(L1, '/admin/tenants/new', {'client_code': 'SHIVA', 'name': 'Shiva Hospital', 'hospital_type': 'Single hospital', 'beds': '180', 'ot_count': '5', 'city': 'Mumbai', 'country': 'India', 'plan_id': '1', 'status': 'active', 'valid_till': '2027-12-31', 'deployment': 'cloud', 'his_type': 'other', 'his_name': 'XYZ HIS', 'features[his_integration]': '1', 'admin_name': 'Shiva Admin', 'admin_username': 'shiva.admin', 'admin_email': 'shiva@example.com'}, '/admin/tenants/new')
check('Client hospital created' in r.text and 'cssd_shiva' in r.text, 'tenant SHIVA created with own DB')
shiva_pw = re.search(r'Temporary password <span class="secret">([^<]+)<', r.text).group(1).replace('&amp;', '&').replace('&#039;', "'")
shiva_id = re.search(r'/admin/tenants/(\d+)/status', r.text).group(1)
r = post(L1, '/admin/tenants/new', {'client_code': 'SHIVA', 'name': 'Dup', 'status': 'trial', 'deployment': 'cloud', 'his_type': 'none', 'admin_name': 'x', 'admin_username': 'xxx', 'admin_email': 'x@example.com'}, '/admin/tenants/new')
check('already used' in r.text, 'duplicate client code blocked')
r = L1.post(B + '/admin/tenants/new', data={'client_code': 'NOCSRF'})
check(r.status_code == 419, 'POST without CSRF rejected (419)')

print('Marketing lead')
P = requests.Session()
r = post(P, '/book-demo', {'name': 'Dr Rao', 'hospital': 'City Care Hospital', 'email': 'bad', 'phone': '98'})
check('valid email' in r.text, 'lead validation works')
r = post(P, '/book-demo', {'name': 'Dr Rao', 'designation': 'Medical Director', 'hospital': 'City Care Hospital', 'email': 'rao@example.com', 'phone': '+91 98200 00000', 'beds': '220', 'ot_count': '6', 'city': 'Pune', 'country': 'India', 'current_his': 'Other', 'interest': 'Full CSSD tracking', 'message': 'Need NABH', 'source_page': '/', 'utm_source': 'google', 'utm_campaign': 'cssd-india'})
check('Thank you, Dr Rao' in r.text, 'lead saved → thank-you page')
r = post(P, '/book-demo', {'name': 'Bot', 'hospital': 'Spam', 'email': 'b@example.com', 'phone': '9999999999', 'website_url': 'http://spam'})
r = get(L1, '/admin/leads')
check('City Care Hospital' in r.text and 'Spam' not in r.text, 'lead in admin list, honeypot dropped bot')
lid = re.search(r'/admin/leads/(\d+)', r.text).group(1)
r = post(L1, f'/admin/leads/{lid}', {'status': 'contacted', 'note': 'Called, demo next week', 'assigned_to': ''})
check('Lead updated' in r.text and 'Called, demo next week' in r.text, 'lead status + note saved')
r = L1.get(B + '/admin/leads?export=csv')
check(r.headers.get('content-type','').startswith('text/csv') and 'City Care' in r.text, 'leads CSV export')
check('New CSSD demo request' in open(ROOT + '/storage/logs/mail.log').read(), 'sales alert email sent')

print('Level 2 — SHIVA hospital admin')
H = requests.Session()
r = post(H, '/login', {'mode': 'password', 'client_code': 'shiva', 'username': 'shiva.admin', 'password': shiva_pw})
check('Check your email' in r.text, 'L2 password ok → OTP')
r = post(H, '/login/otp', {'code': last_otp()})
check('/app/profile' in r.url and 'temporary password' in r.text, 'forced to change temp password')
r = get(H, '/app/users')
check('/app/profile' in r.url, 'other pages blocked until password changed')
r = post(H, '/app/profile', {'action': 'password', 'current_password': shiva_pw, 'new_password': 'Shiva#2026a', 'confirm_password': 'Shiva#2026a'}, '/app/profile')
check('Password changed' in r.text and 'Set-up checklist' in r.text, 'password changed → dashboard')
r = post(H, '/app/m/instruments/new', {'code': 'mayo-sc', 'name': 'Mayo scissors 17cm', 'category_id': '1', 'material': 'Stainless steel', 'max_cycles': '500', 'unit_cost': '850'}, '/app/m/instruments/new')
check('Instrument saved' in r.text and 'MAYO-SC' in r.text, 'instrument created (code upper-cased)')
post(H, '/app/m/instruments/new', {'code': 'ART-FC', 'name': 'Artery forceps', 'category_id': '3', 'unit_cost': '400'}, '/app/m/instruments/new')
r = post(H, '/app/m/instruments/new', {'code': 'MAYO-SC', 'name': 'Dup'}, '/app/m/instruments/new')
check('already exists' in r.text, 'duplicate instrument code blocked')
r = post(H, '/app/m/instrument_sets/new', {'code': 'LAP-01', 'name': 'Laparotomy set', 'department_id': '2', 'pack_type_id': '3', 'method': 'Steam', 'par_level': '4', 'is_critical': '1', 'then': 'compose'}, '/app/m/instrument_sets/new')
check('Composition' in r.text and 'Laparotomy set' in r.text, 'set created → composition page')
set_id = re.search(r'/app/sets/(\d+)', r.url).group(1)
inst = re.findall(r'<option value="(\d+)">', r.text)
post(H, f'/app/sets/{set_id}', {'do': 'add', 'instrument_id': inst[0], 'qty': '2'}, f'/app/sets/{set_id}')
r = post(H, f'/app/sets/{set_id}', {'do': 'add', 'instrument_id': inst[1], 'qty': '6'}, f'/app/sets/{set_id}')
check('>8<' in r.text, 'set composition: 8 pieces total')
r = get(H, f'/app/sets/{set_id}?print=1')
check('CSSD set checklist' in r.text, 'printable checklist')
r = post(H, '/app/m/sterilizers/new', {'branch_id': '1', 'code': 'AC-01', 'name': 'Autoclave 1', 'type': 'Steam', 'chamber_litres': '250'}, '/app/m/sterilizers/new')
check('Sterilizer saved' in r.text, 'sterilizer created')
r = get(H, '/app/roles')
check('CSSD Technician' in r.text and 'OT / Ward Nurse' in r.text, 'default Level 3 roles seeded')
tech_role = re.search(r'<option value="(\d+)"[^>]*>L3 · CSSD Technician', get(H, '/app/users/new').text).group(1)
r = post(H, '/app/users/new', {'name': 'Ravi Technician', 'username': 'ravi', 'emp_code': 'E101', 'role_id': tech_role, 'department_id': '1', 'active': '1'}, '/app/users/new')
check('User created' in r.text, 'Level 3 user created')
ravi_pw = re.search(r'Temporary password <span class="secret">([^<]+)<', r.text).group(1).replace('&amp;', '&')
r = get(H, '/app/m/instruments?export=csv')
check('Mayo scissors' in r.text, 'masters CSV export')
r = get(H, '/app/audit')
check('instrument_sets' in r.text and 'MAYO-SC' in r.text, 'audit trail records changes with values')
r = post(H, '/app/settings', {'hospital_name': 'Shiva Hospital, Mumbai', 'pack_label_prefix': 'SH', 'load_prefix': 'LD', 'indent_prefix': 'IN', 'expiry_alert_days': '7,3,1', 'record_retention_years': '10', 'require_bi_for_implants': '1', 'block_machine_without_bd': '1', 'double_signoff_critical': '1', 'pin_login_enabled': '1', 'ui_language': 'hi'}, '/app/settings')
check('Settings saved' in r.text, 'hospital settings saved')

print('Level 3 — technician')
T = requests.Session()
r = post(T, '/login', {'mode': 'password', 'client_code': 'SHIVA', 'username': 'ravi', 'password': ravi_pw})
check('/app/profile' in r.url, 'L3 login (no OTP) → change temp password')
r = post(T, '/app/profile', {'action': 'password', 'current_password': ravi_pw, 'new_password': 'Ravi#2026a', 'confirm_password': 'Ravi#2026a'}, '/app/profile')
check('CSSD right now' in r.text and 'Set-up checklist' not in r.text, 'L3 dashboard (no admin checklist)')
r = post(T, '/app/profile', {'action': 'pin', 'pin': '4321', 'current_password': 'Ravi#2026a'}, '/app/profile')
check('PIN saved' in r.text, 'PIN set')
check(get(T, '/app/users').status_code == 403, 'L3 blocked from Users (403)')
check(get(T, '/app/m/instruments').status_code == 200, 'technician can view masters')
check(get(T, '/app/m/instruments/new').status_code == 403, 'technician cannot edit masters (403)')
check(get(T, '/app/m/branches/new').status_code == 403, 'technician cannot edit branches (403)')
T2 = requests.Session()
r = post(T2, '/login', {'mode': 'pin', 'client_code': 'SHIVA', 'username': 'E101', 'pin': '4321'}, '/login?mode=pin')
check('CSSD right now' in r.text, 'PIN quick login with employee code')
r = post(requests.Session(), '/login', {'mode': 'pin', 'client_code': 'SHIVA', 'username': 'shiva.admin', 'pin': '1234'}, '/login?mode=pin')
check('incorrect' in r.text, 'Level 2 cannot use PIN login')

print('Lockout')
X = requests.Session()
for i in range(5): r = post(X, '/login', {'mode': 'password', 'client_code': 'SHIVA', 'username': 'ravi', 'password': 'nope'})
r = post(X, '/login', {'mode': 'password', 'client_code': 'SHIVA', 'username': 'ravi', 'password': 'Ravi#2026a'})
check('Too many failed attempts' in r.text or 'locked' in r.text, 'locked after 5 wrong passwords')
r = get(H, '/app/users')
check('Locked' in r.text, 'admin sees Locked badge')
uid = re.search(r'/app/users/(\d+)/action"[^>]*>\s*<input type="hidden" name="_csrf" value="[0-9a-f]+"><input type="hidden" name="do" value="unlock"', r.text)
check(uid is not None, 'unlock button present')

print('Support login & suspension')
r = post(L1, f'/admin/tenants/{shiva_id}/support-login', {'reason': 'Ticket 1042 masters help'}, f'/admin/tenants/{shiva_id}')
check('Caresoft support session' in r.text, 'support login opens hospital with banner')
r = get(L1, '/app/audit')
check('support_login' in r.text, 'support login in hospital audit trail')
post(L1, '/logout', {}, '/app')
r = post(L1, f'/admin/tenants/{shiva_id}/status', {'status': 'suspended'}, f'/admin/tenants/{shiva_id}')
check('Status changed to suspended' in r.text, 'tenant suspended')
r = get(T2, '/app')
check('suspended' in r.text, 'logged-in user kicked out when suspended')
r = post(requests.Session(), '/login', {'mode': 'password', 'client_code': 'SHIVA', 'username': 'shiva.admin', 'password': 'Shiva#2026a'})
check('suspended' in r.text, 'suspended tenant cannot sign in')
post(L1, f'/admin/tenants/{shiva_id}/status', {'status': 'active'}, f'/admin/tenants/{shiva_id}')
r = get(L1, '/admin/audit')
check('tenant_created' in r.text and 'support_login' in r.text, 'platform audit trail')
print(f'\n{ok} passed, {bad} failed'); sys.exit(1 if bad else 0)
