# Phase 2 end-to-end: auto recall on BI positive, recall actions + closure, registers, audits, CAPA, SOPs, environment, training.
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'
MAIL = ROOT + '/storage/logs/mail.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, files=None):
    d = dict(data); d['_csrf'] = csrf(get(s, page or p).text)
    return s.post(B + p, data=d, files=files)
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, DB = 'QUAL', 'cssd_qual'
sql(f"DROP DATABASE IF EXISTS {DB}; DELETE FROM cssd_control.tenants WHERE client_code='{CODE}'; DELETE FROM cssd_control.login_attempts;")
open(MAIL, 'a').close(); mail_start = os.path.getsize(MAIL)

print('Set-up + one full cycle')
L1 = requests.Session()
post(L1, '/admin/login', {'email': 'superadmin@example.com', 'password': 'Admin#2026x'}); post(L1, '/admin/otp', {'code': otp()})
pw = secret(post(L1, '/admin/tenants/new', {'client_code': CODE, 'name': 'Quality Hospital', 'status': 'active', 'deployment': 'cloud', 'his_type': 'none', 'country': 'India', 'valid_till': '2027-12-31', 'admin_name': 'Q Admin', 'admin_username': 'admin', 'admin_email': 'qadmin@example.com'}, '/admin/tenants/new'))
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': 'Qual#2026a', 'confirm_password': 'Qual#2026a'}, '/app/profile')
for code, name in [('SCI', 'Mayo scissors'), ('SCR', 'Bone screwdriver')]: post(A, '/app/m/instruments/new', {'code': code, 'name': name}, '/app/m/instruments/new')
def make_set(code, name, extra, inst):
    r = post(A, '/app/m/instrument_sets/new', dict({'code': code, 'name': name, 'department_id': '2', 'pack_type_id': '2', 'method': 'Steam', 'par_level': '2', 'then': 'compose'}, **extra), '/app/m/instrument_sets/new')
    sid = re.search(r'/app/sets/(\d+)', r.url).group(1)
    opt = {n.strip(): v for v, n in re.findall(r'<option value="(\d+)">([^<]+?) · ', r.text)}
    post(A, f'/app/sets/{sid}', {'do': 'add', 'instrument_id': opt[inst], 'qty': 2}, f'/app/sets/{sid}')
    post(A, f'/app/sets/{sid}/units', {'count': '2'}, f'/app/sets/{sid}')
make_set('LAP', 'Laparotomy set', {}, 'Mayo scissors')
make_set('ORT', 'Ortho implant set', {'is_implant': '1'}, 'Bone screwdriver')
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))
S = {}
for u, role, dept, email in [('tech', 'CSSD Technician', '1', ''), ('sup', 'CSSD Supervisor', '1', 'sup@example.com'), ('nurse', 'OT / Ward Nurse', '2', 'nurse@example.com'), ('icn', 'Infection Control Nurse', '', 'icn@example.com')]:
    p = secret(post(A, '/app/users/new', {'name': u.title() + ' User', 'username': u, 'role_id': roles[role], 'department_id': dept, 'email': email, 'active': '1'}, '/app/users/new'))
    s = requests.Session(); post(s, '/login', {'mode': 'password', 'client_code': CODE, 'username': u, 'password': p})
    post(s, '/app/profile', {'action': 'password', 'current_password': p, 'new_password': 'Pass#2026a', 'confirm_password': 'Pass#2026a'}, '/app/profile'); S[u] = s
T, SU, N, I = S['tech'], S['sup'], S['nurse'], S['icn']
for tag in ['LAP-01', 'LAP-02', 'ORT-01']:
    uid = re.search(r'name="unit_id" value="(\d+)"', get(T, f'/app/receive?code={tag}').text).group(1)
    post(T, '/app/receive', {'unit_id': uid, 'code': tag, 'counted': '1'}, f'/app/receive?code={tag}')
post(T, '/app/clean/load', {'method': 'washer', 'washer_id': '1', 'cycle_ids[]': re.findall(r'name="cycle_ids\[\]" value="(\d+)"', get(T, '/app/clean').text)}, '/app/clean')
post(T, '/app/clean/1/complete', {'result': 'pass'}, '/app/clean')
for c in re.findall(r'/app/pack/(\d+)"', get(T, '/app/pack').text): post(T, f'/app/pack/{c}', {'pack_type_id': '2', 'count_confirmed': '1'}, f'/app/pack/{c}')
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': '3'}, '/app/sterilize'); load = re.search(r'/app/sterilize/load/(\d+)', r.url).group(1)
for pk in ['PK-000001', 'PK-000002', 'PK-000003']: post(T, f'/app/sterilize/load/{load}', {'do': 'add', 'pack_no': pk}, f'/app/sterilize/load/{load}')
post(T, f'/app/sterilize/load/{load}', {'do': 'start'}, f'/app/sterilize/load/{load}')
post(T, f'/app/sterilize/load/{load}', {'do': 'complete', 'physical_ok': '1', 'ci_result': 'pass', 'ci_lot': 'CI-9', 'bi_used': '1', 'bi_lot': 'BI-555', 'bi_result': 'pending', 'temperature_c': '134', 'exposure_min': '4'}, f'/app/sterilize/load/{load}')
r = post(SU, f'/app/release/{load}', {'note': 'Emergency ortho case OT-1, BI incubating', 'early': '1'}, '/app/release')
check('Load released' in r.text, 'implant load early-released with documented reason')
packs = dict(re.findall(r"(PK-\d+)'?\s*\|?\s*", '')) or None
lap1, lap2 = [x for x in sql(f"SELECT c.pack_no FROM {DB}.cycles c JOIN {DB}.instrument_sets s ON s.id=c.set_id WHERE s.code='LAP' ORDER BY c.id").split('\n')]
ort = sql(f"SELECT c.pack_no FROM {DB}.cycles c JOIN {DB}.instrument_sets s ON s.id=c.set_id WHERE s.code='ORT'")
post(T, '/app/issue', {'department_id': '2', 'pack_no': lap1}, '/app/issue'); post(T, '/app/issue', {'department_id': '2', 'pack_no': lap2}, '/app/issue')
r = post(N, '/app/dept', {'do': 'use', 'pack_no': lap1, 'patient_uhid': 'UH500', 'patient_name': 'Sunita Rao', 'procedure_name': 'Laparotomy'}, '/app/dept')
check('linked to patient' in r.text, f'{lap1} used on patient UH500, {lap2} with OT, {ort} in store')

print('BI positive → automatic recall')
r = post(SU, f'/app/release/{load}', {'do': 'bi', 'bi_result': 'fail'}, '/app/release')
check('BI POSITIVE' in r.text, 'BI positive recorded on released load')
rid = sql(f"SELECT id FROM {DB}.recalls WHERE trigger_source='bi_positive'")
check(rid != '', 'recall RC-000001 created automatically')
locs = sql(f"SELECT CONCAT(c.pack_no,':',ri.location,':',ri.action) FROM {DB}.recall_items ri JOIN {DB}.cycles c ON c.id=ri.cycle_id ORDER BY c.pack_no").split('\n')
check(f'{lap1}:patient:pending' in locs and f'{lap2}:department:pending' in locs and f'{ort}:store:quarantined' in locs, 'recall found pack on patient, pack in OT, pack in store (quarantined)')
mails = open(MAIL).read()[mail_start:]
check('URGENT: CSSD recall RC-000001' in mails and 'nurse@example.com' in mails and 'icn@example.com' in mails, 'recall emailed to OT nurse and infection control')
r = post(N, '/app/dept', {'do': 'use', 'pack_no': lap2, 'patient_uhid': 'UH501', 'patient_name': 'X'}, '/app/dept')
check('under recall' in flash(r)[1], 'recalled pack STOPPED at point of use')
r = post(N, '/app/dept', {'do': 'return', 'pack_no': lap2, 'intact': '1'}, '/app/dept')
check(sql(f"SELECT ri.action FROM {DB}.recall_items ri JOIN {DB}.cycles c ON c.id=ri.cycle_id WHERE c.pack_no='{lap2}'") == 'retrieved', 'department return auto-marks recall item retrieved')
check(get(N, '/app/recalls').status_code == 403, 'nurse cannot open recall management (403)')
r = post(I, f'/app/recalls/{rid}/close', {'root_cause': 'Steam penetration issue', 'closure_summary': 'All handled'}, f'/app/recalls/{rid}')
check('still pending' in flash(r)[1], 'cannot close while a pack is pending')
item = re.search(r'name="item_id" value="(\d+)"', get(I, f'/app/recalls/{rid}').text).group(1)
r = post(I, f'/app/recalls/{rid}/item', {'item_id': item, 'action': 'patient_follow_up', 'note': ''}, f'/app/recalls/{rid}')
check('Note who was informed' in flash(r)[1], 'patient follow-up needs a note')
r = post(I, f'/app/recalls/{rid}/item', {'item_id': item, 'action': 'patient_follow_up', 'note': 'ICN informed Dr Mehta 12-Nov 16:00, patient under watch'}, f'/app/recalls/{rid}')
check('Action recorded' in r.text, 'patient follow-up recorded')
r = post(I, f'/app/recalls/{rid}/close', {'root_cause': 'Air leak in chamber door seal', 'closure_summary': 'Seal replaced, BD and BI repeated OK, patient followed up', 'raise_capa': '1'}, f'/app/recalls/{rid}')
check('/app/capa/' in r.url and 'CAPA-000001' in r.text, 'recall closed → CAPA-000001 raised')
r = get(SU, f'/app/trace?q={lap1}')
check('RECALL RC-000001' in r.text and 'Recall patient follow up' in r.text, 'recall steps appear in pack timeline')

print('Registers')
r = get(I, '/app/registers')
check('Biological indicator register' in r.text and 'Recall register' in r.text, 'registers index')
r = get(I, '/app/registers/bowie_dick')
check('BD-77' in r.text, 'Bowie-Dick register')
r = get(I, '/app/registers/sterilizer_loads?print=1')
check('LD-000001' in r.text and '(EARLY)' in r.text and 'CI-9' in r.text and 'Infection control' in r.text, 'printable load register shows early release + lots + signature lines')
r = get(I, '/app/registers/biological')
check('BI-555' in r.text and 'FAIL' in r.text, 'BI register shows positive result')
r = get(I, '/app/registers/patient?export=csv')
check(r.headers['content-type'].startswith('text/csv') and 'UH500' in r.text and r.text.startswith('Used,UHID'), 'patient traceability register CSV')
r = get(I, '/app/registers/recall')
check('RC-000001' in r.text and 'Air leak' in r.text, 'recall register')
check(get(N, '/app/registers/sterilizer_loads').status_code == 403, 'nurse cannot open load register (403)')

print('Audit → CAPA → verification')
r = get(I, '/app/audits/new?template=1')
qs = re.findall(r'name="answer\[(\d+)\]" value="yes"', r.text)
data = {f'answer[{q}]': 'yes' for q in qs}; data[f'answer[{qs[2]}]'] = 'no'; data[f'capa[{qs[2]}]'] = '1'; data[f'remark[{qs[2]}]'] = 'No log since Monday'; data['template_id'] = '1'
icn_id = re.search(r'<option value="(\d+)">Icn User', r.text).group(1); data['capa_owner'] = icn_id
r = post(I, '/app/audits/new', data, '/app/audits/new?template=1')
check('Audit saved' in r.text and '88.9%' in r.text and 'CAPA-000002' in r.text, 'daily checklist 8/9 = 88.9% and CAPA raised for the gap')
capa = re.search(r'/app/capa/(\d+)">CAPA-000002', r.text).group(1)
r = post(I, f'/app/capa/{capa}', {'title': 'Audit gap', 'owner_id': icn_id, 'move': 'done'}, f'/app/capa/{capa}')
check('Root cause and corrective action' in flash(r)[1], 'CAPA cannot be done without root cause + action')
r = post(I, f'/app/capa/{capa}', {'title': 'Audit gap', 'owner_id': icn_id, 'root_cause': 'No owner for the log', 'corrective_action': 'Store in-charge assigned', 'move': 'done'}, f'/app/capa/{capa}')
check('Done — verify' in r.text, 'CAPA marked done')
r = post(I, f'/app/capa/{capa}', {'title': 'Audit gap', 'owner_id': icn_id, 'root_cause': 'x', 'corrective_action': 'y', 'effectiveness_note': 'Checked 7 days of logs', 'move': 'verified'}, f'/app/capa/{capa}')
check('someone other than the owner' in flash(r)[1], 'owner cannot verify own CAPA')
r = post(A, f'/app/capa/{capa}', {'title': 'Audit gap', 'owner_id': icn_id, 'root_cause': 'No owner for the log', 'corrective_action': 'Store in-charge assigned', 'effectiveness_note': 'Checked 7 days of logs, complete', 'move': 'verified'}, f'/app/capa/{capa}')
check('Verified &amp; closed' in r.text or 'Verified & closed' in r.text, 'admin verifies and closes CAPA')
check(get(T, '/app/capa').status_code == 403, 'technician cannot open CAPA (403)')

print('SOP library')
r = post(I, '/app/sops/new', {'code': 'CSSD-SOP-01', 'title': 'Bowie-Dick test', 'version': '1.0', 'category': 'Sterilization', 'content': 'Run the Bowie-Dick test in an empty chamber before the first load every day.', 'read_required': '1'}, '/app/sops/new')
check('SOP published' in r.text, 'SOP published')
lib = get(I, '/app/sops')
check('CSSD-SOP-01' in lib.text and '0 / ' in lib.text, 'SOP library lists SOP with read count')
sop1 = re.search(r'/app/sops/(\d+)', r.url).group(1)
check('SOP(s) for you to read' in get(N, '/app').text, 'nurse sees SOP to read on dashboard')
r = post(N, f'/app/sops/{sop1}/read', {}, f'/app/sops/{sop1}')
check('You confirmed reading' in r.text, 'nurse confirms reading')
r = post(I, '/app/sops/new', {'code': 'CSSD-SOP-01', 'title': 'Bowie-Dick test', 'version': '2.0', 'content': 'Updated text with leak test first.'}, '/app/sops/new', files={'file': ('sop.txt', b'not a pdf', 'text/plain')})
check('Only PDF' in flash(r)[1], 'non-PDF upload rejected')
pdf = b'%PDF-1.4\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF'
r = post(I, '/app/sops/new', {'code': 'CSSD-SOP-01', 'title': 'Bowie-Dick test', 'version': '2.0', 'content': 'Updated text with leak test first.', 'read_required': '1'}, f'/app/sops/new?from={sop1}', files={'file': ('bd.pdf', pdf, 'application/pdf')})
sop2 = re.search(r'/app/sops/(\d+)', r.url).group(1)
check(sql(f"SELECT status FROM {DB}.sops WHERE id={sop1}") == 'superseded' and 'SOP(s) for you to read' in get(N, '/app').text, 'v2 supersedes v1 and nurse must re-read')
r = get(N, f'/app/sops/{sop2}/file')
check(r.headers.get('content-type') == 'application/pdf' and r.content.startswith(b'%PDF'), 'PDF served to logged-in staff')
check(requests.get(B + f'/app/sops/{sop2}/file', allow_redirects=False).status_code == 302, 'PDF not served without login')

print('Environment, training, discrepancies, manual recall')
r = post(T, '/app/environment', {'area': 'sterile_store', 'temperature_c': '27', 'humidity_pct': '55'}, '/app/environment')
check('record the action taken' in flash(r)[1], 'out-of-limit reading needs action')
r = post(T, '/app/environment', {'area': 'sterile_store', 'temperature_c': '27', 'humidity_pct': '55', 'action_taken': 'AC serviced, rechecked 30 min'}, '/app/environment')
check('breach' in r.text.lower() and 'Temperature 27' in r.text, 'breach recorded')
check('temperature / humidity breach' in get(A, '/app').text, 'breach alert on admin dashboard')
tech_id = sql(f"SELECT id FROM {DB}.users WHERE username='tech'")
r = post(I, '/app/training', {'topic': 'Steam sterilizer loading', 'type': 'competency', 'training_date': '2026-11-12', 'result': 'competent', 'valid_till': '2027-11-12', 'trainer': 'Sup User', 'user_ids[]': [tech_id]}, '/app/training')
check('Training recorded' in r.text and '12 Nov 2027' in r.text, 'competency recorded with validity')
uid = re.search(r'name="unit_id" value="(\d+)"', get(T, '/app/receive?code=ORT-02').text).group(1)
ins = re.search(r'name="issue_qty\[(\d+)\]"', get(T, '/app/receive?code=ORT-02').text).group(1)
post(T, '/app/receive', {'unit_id': uid, 'code': 'ORT-02', 'counted': '1', f'issue_qty[{ins}]': '1', f'issue_type[{ins}]': 'missing'}, '/app/receive?code=ORT-02')
did = re.search(r'/app/discrepancies/(\d+)"', get(T, '/app/discrepancies').text).group(1)
r = post(T, f'/app/discrepancies/{did}', {'resolution': 'found', 'note': 'Found in OT-1 tray'}, '/app/discrepancies')
check('Resolved' in r.text and sql(f"SELECT resolution FROM {DB}.cycle_discrepancies WHERE id={did}") == 'found', 'missing instrument resolved')
r = post(I, '/app/recalls/new', {'scope_type': 'sterilizer_period', 'sterilizer_id': '1', 'date_from': '2026-11-01', 'date_to': '2026-11-30', 'reason': 'Door seal fault — all loads this month', 'severity': 'high'}, '/app/recalls/new')
check('Recall started' in r.text and 'RC-000002' in r.text, 'manual recall by sterilizer + period')
r = post(I, '/app/recalls/new', {'scope_type': 'indicator_lot', 'indicator_lot': 'NOPE', 'reason': 'Faulty lot'}, '/app/recalls/new')
check('No sterilized packs' in flash(r)[1], 'empty recall scope refused')
print(f'\n{ok} passed, {bad} failed'); sys.exit(1 if bad else 0)
