# Phase 1 end-to-end: full CSSD cycle + every hard stop. Needs env=dev and the smoke-test super admin.
import os, re, sys, subprocess, requests
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 = bad = 0
def check(cond, msg):
    global ok, bad
    if cond: ok += 1; print('  ✓', msg)
    else: bad += 1; print('  ✗', msg)
def csrf(h):
    m = re.search(r'name="_csrf" value="([0-9a-f]+)"', h); return m.group(1) if m else ''
def otp(): return open(LOG).read().strip().splitlines()[-1].split()[-1]
def get(s, p): return s.get(B + p)
def post(s, p, data, page=None):
    d = dict(data); d['_csrf'] = csrf(get(s, page or p).text)
    return s.post(B + p, data=d)
def flash(r):
    m = re.search(r'class="alert alert-(\w+)"[^>]*>(.*?)</div>', r.text, re.S); return (m.group(1), re.sub('<[^>]+>', '', m.group(2)).strip()) if m else ('', '')
def secret(r): return re.search(r'Temporary password <span class="secret">([^<]+)<', r.text).group(1).replace('&amp;', '&')
def sql(q): return subprocess.run(['mysql', '-uroot', '-N', '-e', q], capture_output=True, text=True).stdout.strip()

CODE = 'CITY'
sql(f"DROP DATABASE IF EXISTS cssd_{CODE.lower()}; DELETE FROM cssd_control.tenants WHERE client_code='{CODE}'; DELETE FROM cssd_control.login_attempts;")

print('Set-up')
L1 = requests.Session()
post(L1, '/admin/login', {'email': 'superadmin@example.com', 'password': 'Admin#2026x'}); post(L1, '/admin/otp', {'code': otp()})
r = post(L1, '/admin/tenants/new', {'client_code': CODE, 'name': 'City Care Hospital', 'status': 'active', 'deployment': 'cloud', 'his_type': 'none', 'country': 'India', 'valid_till': '2027-12-31', 'admin_name': 'City Admin', 'admin_username': 'admin', 'admin_email': 'city@example.com'}, '/admin/tenants/new')
pw = secret(r)
check(sql(f"SELECT COUNT(*) FROM cssd_{CODE.lower()}.schema_migrations WHERE version LIKE '002%'") == '1', 'new client DB has Phase 1 migration applied')

A = requests.Session()
post(A, '/login', {'mode': 'password', 'client_code': CODE, 'username': 'admin', 'password': pw}); post(A, '/login/otp', {'code': otp()})
post(A, '/app/profile', {'action': 'password', 'current_password': pw, 'new_password': 'City#2026a', 'confirm_password': 'City#2026a'}, '/app/profile')
for code, name in [('SCI', 'Mayo scissors'), ('ART', 'Artery forceps'), ('SCR', 'Bone screwdriver')]:
    post(A, '/app/m/instruments/new', {'code': code, 'name': name}, '/app/m/instruments/new')
ids = dict(re.findall(r'<option value="(\d+)">([^<·]+?) ·', get(A, '/app/sets/1').text)) if False else None
def make_set(code, name, method, extra, items):
    r = post(A, '/app/m/instrument_sets/new', dict({'code': code, 'name': name, 'department_id': '2', 'pack_type_id': '2', 'method': method, 'par_level': '2', 'then': 'compose'}, **extra), '/app/m/instrument_sets/new')
    sid = re.search(r'/app/sets/(\d+)', r.url).group(1)
    opts = {n.strip(): v for v, n in re.findall(r'<option value="(\d+)">([^<]+?) · ', r.text)}
    for iname, q in items: post(A, f'/app/sets/{sid}', {'do': 'add', 'instrument_id': opts[iname], 'qty': q}, f'/app/sets/{sid}')
    post(A, f'/app/sets/{sid}/units', {'count': '2'}, f'/app/sets/{sid}')
    return sid
lap = make_set('LAP', 'Laparotomy set', 'Steam', {}, [('Mayo scissors', 2), ('Artery forceps', 6)])
ort = make_set('ORT', 'Ortho implant set', 'Steam', {'is_implant': '1', 'is_critical': '1'}, [('Bone screwdriver', 1)])
eto = make_set('SCOPE', 'Scope set', 'ETO', {}, [('Mayo scissors', 1)])
r = get(A, f'/app/sets/{lap}')
check('LAP-01' in r.text and 'LAP-02' in r.text, 'set units with tags created')
r = get(A, f'/app/labels?tags=LAP-01,LAP-02')
check(r.text.count('<svg') == 2 and 'SET TAG' in r.text, 'set tag labels with barcodes')
post(A, '/app/m/sterilizers/new', {'branch_id': '1', 'code': 'AC1', 'name': 'Autoclave 1', 'type': 'Steam'}, '/app/m/sterilizers/new')
post(A, '/app/m/washers/new', {'branch_id': '1', 'code': 'WD1', 'name': 'Washer 1', 'type': 'Washer-disinfector'}, '/app/m/washers/new')
roles = dict((n, v) for v, n in re.findall(r'<option value="(\d+)"[^>]*>L\d · ([^<]+)<', get(A, '/app/users/new').text))
users = {}
for uname, role, dept in [('tech', 'CSSD Technician', '1'), ('sup', 'CSSD Supervisor', '1'), ('nurse', 'OT / Ward Nurse', '2')]:
    r = post(A, '/app/users/new', {'name': uname.title() + ' User', 'username': uname, 'role_id': roles[role], 'department_id': dept, 'active': '1'}, '/app/users/new')
    users[uname] = secret(r)
S = {}
for u in users:
    s = requests.Session()
    post(s, '/login', {'mode': 'password', 'client_code': CODE, 'username': u, 'password': users[u]})
    post(s, '/app/profile', {'action': 'password', 'current_password': users[u], 'new_password': 'Pass#2026a', 'confirm_password': 'Pass#2026a'}, '/app/profile')
    S[u] = s
T, SU, N = S['tech'], S['sup'], S['nurse']
check('Indents' in get(N, '/app').text and 'Receive used sets' not in get(N, '/app').text, 'nurse menu shows only department screens')

print('Indent')
r = post(N, '/app/indents/new', {'type': 'stat', 'set_id[]': [lap], 'qty[]': ['1'], 'notes': 'OT-1 laparotomy'}, '/app/indents/new')
check('Indent raised' in r.text and 'IN-000001' in r.text, 'nurse raises STAT indent IN-000001 (own department)')
indent_id = re.search(r'/app/indents/(\d+)', r.url).group(1)

print('Receive → clean → pack')
r = post(T, '/app/receive', {'unit_id': '1', 'code': 'LAP-01'}, '/app/receive?code=LAP-01')
check('Tick' in flash(r)[1], 'receiving refused without count confirmation')
r = post(T, '/app/receive', {'unit_id': '1', 'code': 'LAP-01', 'counted': '1'}, '/app/receive?code=LAP-01')
check('Count OK' in r.text, 'LAP-01 received (first intake)')
r = post(T, '/app/receive', {'unit_id': '1', 'code': 'LAP-01', 'counted': '1'}, '/app/receive?code=LAP-01')
check('already in CSSD' in flash(r)[1], 'double receiving blocked')
r = get(T, '/app/receive?code=ORT-01')
ort_unit = re.search(r'name="unit_id" value="(\d+)"', r.text).group(1)
instr = re.search(r'name="issue_qty\[(\d+)\]"', r.text).group(1)
r = post(T, '/app/receive', {'unit_id': ort_unit, 'code': 'ORT-01', 'counted': '1', f'issue_qty[{instr}]': '1', f'issue_type[{instr}]': 'damaged'}, '/app/receive?code=ORT-01')
check('discrepancies logged' in r.text, 'ORT-01 received with damaged-item discrepancy')
cyc = re.findall(r'name="cycle_ids\[\]" value="(\d+)"', get(T, '/app/clean').text)
r = post(T, '/app/clean/load', {'method': 'washer', 'washer_id': '1', 'program': '93C', 'cycle_ids[]': cyc}, '/app/clean')
check('Cleaning load started' in r.text and 'WL-000001' in r.text, 'washer load WL-000001 with 2 sets')
r = post(T, '/app/clean/1/complete', {'result': 'pass', 'temperature_c': '93'}, '/app/clean')
check('moved to packing' in r.text, 'cleaning passed → packing queue')
packq = re.findall(r'/app/pack/(\d+)"', get(T, '/app/pack').text)
lap_c, ort_c = packq[0], packq[1]
r = post(T, f'/app/pack/{lap_c}', {'pack_type_id': '2'}, f'/app/pack/{lap_c}')
check('Confirm the instrument count' in flash(r)[1], 'packing refused without count confirmation')
r = post(T, f'/app/pack/{lap_c}', {'pack_type_id': '2', 'count_confirmed': '1'}, f'/app/pack/{lap_c}')
check('Packed as PK-000001' in r.text, 'LAP packed as PK-000001')
sup_id = re.search(r'<option value="(\d+)">Sup User', get(T, f'/app/pack/{ort_c}').text).group(1)
r = post(T, f'/app/pack/{ort_c}', {'pack_type_id': '3', 'count_confirmed': '1', 'checker_id': sup_id, 'checker_secret': 'wrong'}, f'/app/pack/{ort_c}')
check('Checker PIN / password is wrong' in flash(r)[1], 'critical set: wrong checker secret refused')
r = post(T, f'/app/pack/{ort_c}', {'pack_type_id': '3', 'count_confirmed': '1', 'checker_id': sup_id, 'checker_secret': 'Pass#2026a'}, f'/app/pack/{ort_c}')
check('Packed as PK-000002' in r.text, 'implant set packed with double sign-off PK-000002')
r = get(T, '/app/labels?packs=PK-000001,PK-000002')
check(r.text.count('<svg') == 2 and 'EXP' in r.text, 'pack labels render with barcode + expiry')
open('/tmp/label.html', 'w').write(r.text)

print('Sterilize')
r = post(T, '/app/sterilize/load', {'sterilizer_id': '1', 'cycle_type_id': '3'}, '/app/sterilize')
check('blocked' in flash(r)[1], 'steam load blocked until Bowie-Dick passes')
post(T, '/app/sterilize/test', {'sterilizer_id': '1', 'test_type': 'bowie_dick', 'result': 'fail'}, '/app/sterilize')
r = post(T, '/app/sterilize/load', {'sterilizer_id': '1', 'cycle_type_id': '3'}, '/app/sterilize')
check('blocked' in flash(r)[1], 'still blocked after a failed Bowie-Dick')
post(T, '/app/sterilize/test', {'sterilizer_id': '1', 'test_type': 'bowie_dick', 'result': 'pass', 'indicator_lot': 'BD-77'}, '/app/sterilize')
r = post(T, '/app/sterilize/load', {'sterilizer_id': '1', 'cycle_type_id': '7'}, '/app/sterilize')
check('Choose a Steam cycle' in flash(r)[1], 'ETO cycle type rejected for a steam sterilizer')
r = post(T, '/app/sterilize/load', {'sterilizer_id': '1', 'cycle_type_id': '3'}, '/app/sterilize')
check('LD-000001' in r.text, 'load LD-000001 opened after BD pass')
load = re.search(r'/app/sterilize/load/(\d+)', r.url).group(1)
for pk in ['PK-000001', 'PK-000002']:
    r = post(T, f'/app/sterilize/load/{load}', {'do': 'add', 'pack_no': pk}, f'/app/sterilize/load/{load}')
check('Contains implant set' in r.text, 'packs added; load flagged as implant')
r = post(T, f'/app/sterilize/load/{load}', {'do': 'add', 'pack_no': 'PK-000001'}, f'/app/sterilize/load/{load}')
check('cannot add' in flash(r)[1], 'same pack cannot be loaded twice')
post(T, f'/app/sterilize/load/{load}', {'do': 'start'}, f'/app/sterilize/load/{load}')
r = post(T, f'/app/sterilize/load/{load}', {'do': 'complete', 'physical_ok': '1', 'ci_result': 'pass', 'bi_used': '1', 'bi_lot': '', 'bi_result': 'pending', 'temperature_c': '134'}, f'/app/sterilize/load/{load}')
check('lot number' in flash(r)[1], 'BI lot required for implant load')
r = post(T, f'/app/sterilize/load/{load}', {'do': 'complete', 'physical_ok': '1', 'ci_result': 'pass', 'bi_used': '1', 'bi_lot': 'BI-2201', 'bi_result': 'pending', 'temperature_c': '134', 'exposure_min': '4'}, f'/app/sterilize/load/{load}')
check('waiting for supervisor release' in r.text, 'cycle recorded, awaiting release')

print('Release')
check(get(T, '/app/release').status_code == 403, 'technician cannot release (403)')
r = get(SU, '/app/release')
check('waiting for the biological indicator' in r.text, 'implant load blocked: BI pending')
r = post(SU, f'/app/release/{load}', {'note': ''}, '/app/release')
check('biological indicator' in flash(r)[1], 'normal release refused while BI pending')
r = post(SU, f'/app/release/{load}', {'note': 'short', 'early': '1'}, '/app/release')
check('documented reason' in flash(r)[1], 'early release needs a 10+ char reason')
r = post(SU, f'/app/release/{load}', {'do': 'bi', 'bi_result': 'pass'}, '/app/release')
check('BI pass recorded' in r.text, 'BI pass recorded')
r = post(SU, f'/app/release/{load}', {'note': 'All indicators OK'}, '/app/release')
check('Load released' in r.text, 'supervisor releases load')
check(sql(f"SELECT COUNT(*) FROM cssd_city.cycles WHERE status='in_store'") == '2', 'both packs sterile in store')

print('Issue & use')
r = post(T, '/app/issue', {'indent_id': indent_id, 'pack_no': 'PK-000002'}, f'/app/issue?indent={indent_id}')
check('not pending on indent' in flash(r)[1], 'wrong set for the indent blocked at issue')
r = post(T, '/app/issue', {'indent_id': indent_id, 'pack_no': 'PK-000001'}, f'/app/issue?indent={indent_id}')
check('Issued PK-000001' in r.text, 'PK-000001 issued against indent')
check(sql(f"SELECT status FROM cssd_city.indents WHERE id={indent_id}") == 'issued', 'indent fully issued')
r = get(N, '/app/dept')
check('PK-000001' in r.text and 'Not acknowledged' in r.text, 'nurse sees pack in department')
post(N, '/app/dept', {'do': 'ack', 'pack_no': 'PK-000001'}, '/app/dept')
r = post(N, '/app/dept', {'do': 'use', 'pack_no': 'PK-000001', 'patient_uhid': 'uh123', 'patient_name': 'Ramesh Patil', 'procedure_name': 'Laparotomy'}, '/app/dept')
check('Pack linked to patient' in r.text, 'pack scanned to patient UH123')
check(get(N, '/app/receive').status_code == 403, 'nurse cannot open CSSD receiving (403)')

print('Expiry & failed load')
r = post(T, '/app/issue', {'department_id': '2', 'pack_no': 'PK-000002'}, '/app/issue')
sql("UPDATE cssd_city.cycles SET expiry_date = CURDATE() - INTERVAL 1 DAY WHERE pack_no='PK-000002'")
check(sql("SELECT status FROM cssd_city.cycles WHERE pack_no='PK-000002'") == 'issued', 'direct issue without indent works')
r = post(N, '/app/dept', {'do': 'use', 'pack_no': 'PK-000002', 'patient_uhid': 'UH9', 'patient_name': 'X'}, '/app/dept')
check('expired' in flash(r)[1].lower(), 'expired pack STOPPED at point of use')
r = post(N, '/app/dept', {'do': 'return', 'pack_no': 'PK-000002', 'intact': '1'}, '/app/dept')
check('Return recorded' in r.text, 'nurse returns expired pack')
r = post(T, '/app/store', {'do': 'restock', 'pack_no': 'PK-000002'}, '/app/store')
check('expired' in flash(r)[1].lower(), 'expired returned pack cannot be restocked')
r = post(T, '/app/store', {'do': 'reject', 'pack_no': 'PK-000002'}, '/app/store')
check('full reprocessing' in r.text, 'returned pack sent for full reprocessing')

print('Close the loop')
r = post(T, '/app/receive', {'unit_id': '1', 'code': 'LAP-01', 'counted': '1'}, '/app/receive?code=LAP-01')
check('Count OK' in r.text, 'used LAP-01 received back — new cycle')
check(sql("SELECT close_reason FROM cssd_city.cycles WHERE pack_no='PK-000001'") == 'reprocessed', 'previous cycle closed')
r = get(SU, '/app/trace?q=PK-000001')
for ev in ['Received', 'Cleaned', 'Packed', 'Loaded', 'Released', 'Issued', 'Acknowledged', 'Used', 'Closed']:
    if ev not in r.text: print('    missing', ev)
check(all(ev in r.text for ev in ['Received', 'Cleaned', 'Packed', 'Loaded', 'Released', 'Issued', 'Used', 'Closed']) and 'UH123' in r.text, 'trace shows full chain for PK-000001')
r = get(SU, '/app/trace?q=UH123')
check('PK-000001' in r.text and 'LD-000001' in r.text, 'trace by patient UHID → pack + load')

print('Failed load')
post(T, '/app/clean/load', {'method': 'manual', 'cycle_ids[]': re.findall(r'name="cycle_ids\[\]" value="(\d+)"', get(T, '/app/clean').text)}, '/app/clean')
post(T, '/app/clean/2/complete', {'result': 'pass'}, '/app/clean')
c = sql("SELECT c.id FROM cssd_city.cycles c JOIN cssd_city.instrument_sets s ON s.id=c.set_id WHERE c.status='cleaned' AND s.code='LAP' LIMIT 1")
r = post(T, f'/app/pack/{c}', {'pack_type_id': '2', 'count_confirmed': '1'}, f'/app/pack/{c}')
pk = re.search(r'Packed as (PK-\d+)', r.text).group(1)
r = post(T, '/app/sterilize/load', {'sterilizer_id': '1', 'cycle_type_id': '3'}, '/app/sterilize'); l2 = re.search(r'/app/sterilize/load/(\d+)', r.url).group(1)
post(T, f'/app/sterilize/load/{l2}', {'do': 'add', 'pack_no': pk}, f'/app/sterilize/load/{l2}')
post(T, f'/app/sterilize/load/{l2}', {'do': 'start'}, f'/app/sterilize/load/{l2}')
r = post(T, f'/app/sterilize/load/{l2}', {'do': 'complete', 'physical_ok': '1', 'ci_result': 'fail'}, f'/app/sterilize/load/{l2}')
check('Load FAILED' in r.text, 'chemical indicator fail → load FAILED')
r = post(T, '/app/issue', {'department_id': '2', 'pack_no': pk}, '/app/issue')
check('cannot issue' in flash(r)[1], 'quarantined pack cannot be issued')
r = get(T, '/app/store')
check('Quarantined' in r.text and pk in r.text, 'quarantined pack listed in store')
r = post(T, '/app/store', {'do': 'reprocess', 'pack_no': pk, 'reason': 'Failed load'}, '/app/store')
check('Sent for reprocessing' in r.text and sql(f"SELECT close_reason FROM cssd_city.cycles WHERE pack_no='{pk}'") == 'failed_load', 'quarantined pack reprocessed (closed as failed_load)')
r = get(A, '/app')
check('CSSD right now' in r.text and 'Alerts' in r.text, 'admin dashboard stage board + alerts')
print(f'\n{ok} passed, {bad} failed'); sys.exit(1 if bad else 0)
