# Phase 3 end-to-end: API keys, REST, HL7 v2, FHIR, CSV, OT schedule → auto-indent, point-of-use with surgery,
# patient charges, signed webhooks (needs a receiver: php -S localhost:8099 /tmp/hook.php), alerts, SSO, feature gate.
import os, re, sys, json, time, hmac, hashlib, subprocess, requests, datetime
B = os.environ.get('CSSD_URL', 'http://localhost:8080')
HOOK = os.environ.get('HOOK_URL', 'http://localhost:8099')
HOOKLOG = '/tmp/hooks.jsonl'
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
LOG, MAIL = ROOT + '/storage/logs/otp.log', 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()
def hooks(): return [json.loads(l) for l in open(HOOKLOG)] if os.path.exists(HOOKLOG) else []
CODE, DB = 'INTG', 'cssd_intg'
TOM = (datetime.date.today() + datetime.timedelta(days=1)).isoformat()
sql(f"DROP DATABASE IF EXISTS {DB}; DELETE FROM cssd_control.tenants WHERE client_code='{CODE}'; DELETE FROM cssd_control.login_attempts;")
if os.path.exists(HOOKLOG): os.remove(HOOKLOG)
open(MAIL, 'a').close(); mail0 = os.path.getsize(MAIL)

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': 'Integration Hospital', 'status': 'active', 'deployment': 'cloud', 'his_type': 'caresoft', 'country': 'India', 'valid_till': '2027-12-31',
    'features[his_integration]': '1', 'admin_name': 'I Admin', 'admin_username': 'admin', 'admin_email': 'iadmin@example.com'}, '/admin/tenants/new')
pw = secret(r); tid = re.search(r'/admin/tenants/(\d+)/status', r.text).group(1)
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': 'Intg#2026a', 'confirm_password': 'Intg#2026a'}, '/app/profile')
post(A, '/app/m/departments/2', {'branch_id': '1', 'code': 'OT1', 'name': 'Main OT complex', 'type': 'OT', 'his_ref': 'OT-MAIN'}, '/app/m/departments/2')
post(A, '/app/m/instruments/new', {'code': 'SCI', 'name': 'Mayo scissors'}, '/app/m/instruments/new')
r = post(A, '/app/m/instrument_sets/new', {'code': 'LAP', 'name': 'Laparotomy set', 'department_id': '2', 'pack_type_id': '2', 'method': 'Steam', 'par_level': '2', 'patient_charge': '500', 'his_service_code': 'SRV-CSSD-LAP', 'then': 'compose'}, '/app/m/instrument_sets/new')
sid = re.search(r'/app/sets/(\d+)', r.url).group(1)
post(A, f'/app/sets/{sid}', {'do': 'add', 'instrument_id': re.search(r'<option value="(\d+)">Mayo', r.text).group(1), 'qty': 2}, f'/app/sets/{sid}')
post(A, f'/app/sets/{sid}/units', {'count': '2'}, f'/app/sets/{sid}')
r = post(A, '/app/m/procedures/new', {'name': 'Laparotomy', 'speciality': 'General surgery', 'department_id': '2', 'his_ref': 'SRV-LAP'}, '/app/m/procedures/new')
proc = sql(f"SELECT id FROM {DB}.procedures WHERE his_ref='SRV-LAP'")
r = post(A, f'/app/procedures/{proc}', {'set_id': sid, 'qty': '1'}, f'/app/procedures/{proc}')
check('Preference card saved' in r.text and 'Laparotomy set' in r.text, 'preference card: Laparotomy → 1 × Laparotomy set')
post(A, '/app/m/surgeons/new', {'name': 'Dr Mehta', 'his_ref': 'DR-12'}, '/app/m/surgeons/new')
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.intg@example.com'), ('nurse', 'OT / Ward Nurse', '2', '')]:
    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 = S['tech'], S['sup'], S['nurse']

print('API keys & REST')
r = post(A, '/app/integrations/keys', {'name': 'Caresoft HIS production'}, '/app/integrations')
key = re.search(r'(cssd_INTG_[a-f0-9]{40})', r.text).group(1)
check(key and 'not shown again' in r.text, 'API key created and shown once')
H = {'Authorization': 'Bearer ' + key}
check(requests.get(B + '/api/v1/ping').status_code == 401, 'no key → 401')
check(requests.get(B + '/api/v1/ping', headers={'Authorization': 'Bearer cssd_INTG_' + '0' * 40}).status_code == 401, 'wrong key → 401')
r = requests.get(B + '/api/v1/ping', headers=H)
check(r.status_code == 200 and r.json()['client_code'] == 'INTG', 'ping with key → 200')
r = requests.post(B + '/api/v1/patients', headers=H, json={'patients': [{'uhid': 'uh2001', 'name': 'Ramesh Patil', 'gender': 'M', 'ip_no': 'IP-5521', 'ward': 'Surgery'}, {'uhid': 'UH2009'}]})
check(r.status_code == 200 and r.json()['saved'] == 1 and len(r.json()['errors']) == 1, 'patients: 1 saved, 1 validation error reported')
r = requests.post(B + '/api/v1/surgeries', headers=H, json={'surgeries': [
    {'his_ref': 'OTB-1', 'surgery_at': f'{TOM} 09:30', 'ot_code': 'OT-MAIN', 'patient_uhid': 'UH2001', 'patient_name': 'Ramesh Patil', 'ip_no': 'IP-5521', 'procedure_code': 'SRV-LAP', 'surgeon_code': 'DR-12'},
    {'his_ref': 'OTB-2', 'surgery_at': f'{TOM} 12:00', 'ot_code': 'OT1', 'patient_uhid': 'UH2003', 'patient_name': 'Asha K', 'procedure_name': 'Thyroidectomy'}]})
res = r.json()['results']
check(r.status_code == 200 and res[0]['mapped_ot'] and res[0]['mapped_procedure'] and res[0]['mapped_surgeon'] and not res[1]['mapped_procedure'], 'OT schedule: OT / procedure / surgeon mapped by HIS codes; unknown procedure flagged')
hl7_adt = f"MSH|^~\\&|HIS|HOSP|CSSD|HOSP|20261112183000||ADT^A01|M1|P|2.5\rPID|||UH2002||Shah^Meena||19800101|F|||||9811111111\rPV1||I|Surgery^R2^B5||||||||||||||||IP-7000"
r = requests.post(B + '/api/v1/hl7', headers=H, data=hl7_adt)
check(r.status_code == 200 and 'MSA|AA|M1' in r.text and sql(f"SELECT CONCAT(name,'|',ip_no,'|',bed) FROM {DB}.his_patients WHERE uhid='UH2002'") == 'Meena Shah|IP-7000|B5', 'HL7 ADT^A01 → patient saved, ACK AA')
siu = f"MSH|^~\\&|HIS|HOSP|CSSD|HOSP|20261112183000||SIU^S12|M2|P|2.5\rSCH|OTB-3\rPID|||UH2002||Shah^Meena\rAIS|1||SRV-LAP^Laparotomy|{TOM.replace('-', '')}1100\rAIP|1||DR-12^Mehta^Anil\rAIL|1||OT1"
r = requests.post(B + '/api/v1/hl7', headers=H, data=siu)
check('MSA|AA|M2' in r.text and sql(f"SELECT status FROM {DB}.surgeries WHERE his_ref='OTB-3'") == 'scheduled', 'HL7 SIU^S12 → surgery booked')
r = requests.post(B + '/api/v1/hl7', headers=H, data=siu.replace('SIU^S12|M2', 'SIU^S15|M3'))
check('MSA|AA|M3' in r.text and sql(f"SELECT status FROM {DB}.surgeries WHERE his_ref='OTB-3'") == 'cancelled', 'HL7 SIU^S15 → surgery cancelled')
r = requests.post(B + '/api/v1/hl7', headers=H, data='PID|||X')
check(r.status_code == 400 and 'MSA|AR' in r.text, 'HL7 without MSH → AR')
r = requests.post(B + '/api/v1/fhir/Patient', headers=H, json={'resourceType': 'Patient', 'identifier': [{'value': 'UH2004'}], 'name': [{'given': ['Vikram'], 'family': 'Rao'}], 'gender': 'male', 'birthDate': '1975-03-03'})
check(r.status_code == 200 and sql(f"SELECT name FROM {DB}.his_patients WHERE uhid='UH2004'") == 'Vikram Rao', 'FHIR Patient → saved')
r = requests.post(B + '/api/v1/fhir/Appointment', headers=H, json={'resourceType': 'Appointment', 'id': 'APT-9', 'status': 'booked', 'start': f'{TOM}T15:00:00+05:30',
    'serviceType': [{'coding': [{'code': 'SRV-LAP', 'display': 'Laparotomy'}]}], 'participant': [{'actor': {'reference': 'Patient/UH2004', 'display': 'Vikram Rao'}}, {'actor': {'reference': 'Location/OT-MAIN'}}]})
check(r.status_code == 200 and sql(f"SELECT procedure_id IS NOT NULL FROM {DB}.surgeries WHERE his_ref='APT-9'") == '1', 'FHIR Appointment → surgery booked and mapped')
sql(f"UPDATE {DB}.settings SET value='12' WHERE `key`='api_rate_per_minute'")
codes = [requests.get(B + '/api/v1/ping', headers=H).status_code for _ in range(6)]
check(429 in codes, 'rate limit returns 429')
sql(f"UPDATE {DB}.settings SET value='600' WHERE `key`='api_rate_per_minute'")

print('Webhooks')
r = post(A, '/app/integrations/webhooks', {'preset': 'caresoft_his', 'name': 'HIS billing', 'url': HOOK + '/hook'}, '/app/integrations')
wid = re.search(r'/app/integrations/webhooks/(\d+)', r.url).group(1)
wsecret = re.search(r'Secret: <span class="secret"[^>]*>([a-f0-9]+)<', r.text).group(1)
r = post(A, f'/app/integrations/webhooks/{wid}', {'do': 'test'}, f'/app/integrations/webhooks/{wid}')
h = [x for x in hooks() if x['event'] == 'test']
good_sig = h and h[0]['sig'] == 'sha256=' + hmac.new(wsecret.encode(), h[0]['body'].encode(), hashlib.sha256).hexdigest()
check('Test delivered' in r.text and good_sig, 'test webhook delivered with valid HMAC signature')
post(A, '/app/integrations/webhooks', {'preset': 'careipc', 'name': 'CareIPC', 'url': HOOK + '/fail'}, '/app/integrations')
post(A, '/app/integrations/settings', {'patient_billing_enabled': '1', 'auto_indent_time': '18:00', 'auto_indent_lead_minutes': '60', 'api_rate_per_minute': '600'}, '/app/integrations')

print('OT schedule → auto-indent')
r = get(T, f'/app/ot-schedule?date={TOM}')
check('Ramesh Patil' in r.text and 'Vikram Rao' in r.text and 'Not mapped' in r.text and 'Cancelled' in r.text, 'OT list shows HIS cases incl. unmapped + cancelled')
r = post(T, '/app/ot-schedule/indent', {'date': TOM}, f'/app/ot-schedule?date={TOM}')
check('Indents raised: IN-000001' in r.text and '1 surgery(ies) have no preference card' in r.text, 'one indent for OT1 raised; unmapped surgery reported')
check(sql(f"SELECT CONCAT(i.type,'|',x.qty) FROM {DB}.indents i JOIN {DB}.indent_items x ON x.indent_id=i.id") == 'ot_schedule|2', 'indent has 2 × Laparotomy set (2 mapped cases, cancelled one excluded)')
r = post(T, '/app/ot-schedule/indent', {'date': TOM}, f'/app/ot-schedule?date={TOM}')
check('No new indents' in r.text, 'running again does not duplicate indents')
check('Surgery without preference card' in open(MAIL).read()[mail0:], 'no-preference-card alert emailed to supervisor')
requests.post(B + '/api/v1/surgeries', headers=H, json={'his_ref': 'OTB-1', 'surgery_at': f'{TOM} 09:30', 'ot_code': 'OT-MAIN', 'patient_uhid': 'UH2001', 'patient_name': 'Ramesh Patil', 'procedure_code': 'SRV-LAP', 'status': 'cancelled'})
check('CANCELLED by HIS' in sql(f"SELECT notes FROM {DB}.indents LIMIT 1"), 'HIS cancels a case after indenting → indent flagged for CSSD')
requests.post(B + '/api/v1/surgeries', headers=H, json={'his_ref': 'OTB-1', 'surgery_at': f'{TOM} 09:30', 'ot_code': 'OT-MAIN', 'patient_uhid': 'UH2001', 'patient_name': 'Ramesh Patil', 'ip_no': 'IP-5521', 'procedure_code': 'SRV-LAP', 'surgeon_code': 'DR-12'})
sql(f"UPDATE {DB}.settings SET value='1' WHERE `key`='auto_indent_enabled'; UPDATE {DB}.settings SET value='00:00' WHERE `key`='auto_indent_time'")
out = subprocess.run(['php', ROOT + '/install/worker.php'], capture_output=True, text=True).stdout
check(f'{CODE}: ' in out and 'auto-indent' in out and sql(f"SELECT value FROM {DB}.settings WHERE `key`='auto_indent_last_run'") == datetime.date.today().isoformat(), 'cron worker runs auto-indent once a day')

print('Cycle → use with surgery → charge + webhooks')
for tag in ['LAP-01', 'LAP-02']:
    u = re.search(r'name="unit_id" value="(\d+)"', get(T, f'/app/receive?code={tag}').text).group(1)
    post(T, '/app/receive', {'unit_id': u, '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': 'fail'}, '/app/sterilize')
check('CSSD alert: Bowie-Dick / leak test failed' in open(MAIL).read()[mail0:] and 'sup.intg@example.com' in open(MAIL).read()[mail0:], 'Bowie-Dick failure alert emailed to supervisor')
post(T, '/app/sterilize/test', {'sterilizer_id': '1', 'test_type': 'bowie_dick', 'result': 'pass'}, '/app/sterilize')
r = post(T, '/app/sterilize/load', {'sterilizer_id': '1', 'cycle_type_id': '3'}, '/app/sterilize'); ld = re.search(r'/app/sterilize/load/(\d+)', r.url).group(1)
for pk in ['PK-000001', 'PK-000002']: post(T, f'/app/sterilize/load/{ld}', {'do': 'add', 'pack_no': pk}, f'/app/sterilize/load/{ld}')
post(T, f'/app/sterilize/load/{ld}', {'do': 'start'}, f'/app/sterilize/load/{ld}')
post(T, f'/app/sterilize/load/{ld}', {'do': 'complete', 'physical_ok': '1', 'ci_result': 'pass'}, f'/app/sterilize/load/{ld}')
post(SU, f'/app/release/{ld}', {'note': ''}, '/app/release')
ind = sql(f"SELECT id FROM {DB}.indents LIMIT 1")
for pk in ['PK-000001', 'PK-000002']: post(T, '/app/issue', {'indent_id': ind, 'pack_no': pk}, f'/app/issue?indent={ind}')
sql(f"UPDATE {DB}.surgeries SET surgery_at = CONCAT(CURDATE(), ' ', TIME(surgery_at)) WHERE his_ref IN ('OTB-1','APT-9')")
r = get(N, '/app/dept')
check("Today&#039;s surgeries" in r.text or "Today's surgeries" in r.text, 'nurse sees today\'s surgeries at point of use')
lk = get(N, '/app/lookup/patient?uhid=uh2002').json()
check(lk['found'] and lk['patient']['name'] == 'Meena Shah', 'UHID lookup returns HIS patient')
surg1 = sql(f"SELECT id FROM {DB}.surgeries WHERE his_ref='OTB-1'")
r = post(N, '/app/dept', {'do': 'use', 'pack_no': 'PK-000001', 'surgery_id': surg1, 'patient_uhid': 'UH2001', 'patient_name': 'Ramesh Patil', 'ip_no': 'IP-5521', 'procedure_name': 'Laparotomy'}, '/app/dept')
check('linked to patient' in r.text and sql(f"SELECT status FROM {DB}.surgeries WHERE id={surg1}") == 'done', 'pack used against the surgery; surgery marked done')
ch = sql(f"SELECT CONCAT(service_code,'|',amount,'|',status) FROM {DB}.charges")
check(ch == 'SRV-CSSD-LAP|500.00|pending', 'patient charge ₹500 created with HIS service code')
ev = [x['event'] for x in hooks() if x['path'] == '/hook']
used = [json.loads(x['body']) for x in hooks() if x['event'] == 'pack.used']
check('pack.used' in ev and 'charge.created' in ev and used and used[0]['data']['surgery_ref'] == 'OTB-1', 'webhooks pack.used (with surgery_ref) + charge.created delivered to HIS')
fails = sql(f"SELECT CONCAT(status,'|',attempts) FROM {DB}.webhook_deliveries d JOIN {DB}.webhooks w ON w.id=d.webhook_id WHERE w.name='CareIPC' AND d.event='pack.used'")
check(fails == 'pending|1', 'failing receiver: delivery kept for retry with backoff')

print('API: pack status, use, charges, recalls')
r = requests.get(B + '/api/v1/packs/PK-000001', headers=H).json()
check(r['safe_to_use'] is False and r['patient_uhid'] == 'UH2001', 'GET pack → used, not safe to use')
r = requests.get(B + '/api/v1/packs/PK-000002', headers=H).json()
check(r['safe_to_use'] is True and r['load_status'] == 'released', 'GET pack → issued pack safe to use')
r = requests.post(B + '/api/v1/packs/PK-000002/use', headers=H, json={'surgery_ref': 'APT-9'})
check(r.status_code == 200 and r.json()['patient_uhid'] == 'UH2004', 'HIS links pack to patient via surgery_ref')
r = requests.post(B + '/api/v1/packs/PK-000002/use', headers=H, json={'surgery_ref': 'APT-9'})
check(r.status_code == 422, 'using the same pack twice → 422')
r = requests.get(B + '/api/v1/patients/UH2001/packs', headers=H).json()
check(len(r['packs']) == 1 and r['packs'][0]['pack_no'] == 'PK-000001', 'patient pack history for EMR')
r = requests.get(B + '/api/v1/charges', headers=H).json()
check(len(r['charges']) == 2 and r['charges'][0]['amount'] == 500.0, 'HIS pulls 2 pending charges')
cid = r['charges'][0]['id']
r = requests.post(B + f'/api/v1/charges/{cid}/posted', headers=H, json={'his_ref': 'BILL-77'})
r2 = requests.post(B + f'/api/v1/charges/{cid}/posted', headers=H, json={'his_ref': 'BILL-77'})
check(r.status_code == 200 and r2.status_code == 409, 'charge marked posted; double post → 409')
check(requests.get(B + '/api/v1/recalls', headers=H).json()['recalls'] == [], 'recalls endpoint')

print('SSO, CSV, log, feature gate')
ssec = sql(f"SELECT value FROM {DB}.settings WHERE `key`='sso_secret'")
def sso(user, ts=None, sig=None):
    ts = str(ts or int(time.time())); sig = sig or hmac.new(ssec.encode(), f'{CODE}|{user}|{ts}'.encode(), hashlib.sha256).hexdigest()
    s = requests.Session(); return s, s.get(B + f'/sso?client={CODE}&user={user}&ts={ts}&sig={sig}&to=app/dept')
s, r = sso('nurse')
check('SSO is switched off' in r.text, 'SSO refused while disabled')
post(A, '/app/integrations/settings', {'sso_enabled': '1', 'patient_billing_enabled': '1', 'auto_indent_time': '00:00', 'auto_indent_lead_minutes': '60', 'api_rate_per_minute': '600'}, '/app/integrations')
ts = int(time.time()); sig = hmac.new(ssec.encode(), f'{CODE}|nurse|{ts}'.encode(), hashlib.sha256).hexdigest()
s, r = sso('nurse', ts, sig)
check(r.url.endswith('/app/dept') and 'Department packs' in r.text, 'SSO signed link opens CSSD as the nurse')
s, r = sso('nurse', ts, sig)
check('already used' in r.text, 'SSO link cannot be replayed')
s, r = sso('nurse', int(time.time()) - 600)
check('expired' in r.text, 'expired SSO link refused')
s, r = sso('nurse', sig='0' * 64)
check('invalid signature' in r.text, 'bad SSO signature refused')
csv1 = 'uhid,name,ip_no\nUH3001,Kiran Joshi,IP-9\n,NoUhid,\n'
r = post(A, '/app/integrations/import', {'kind': 'patients'}, '/app/integrations/import', files={'file': ('p.csv', csv1, 'text/csv')})
check('1 patients saved' in r.text and 'Line 3' in r.text, 'CSV patients import with row error report')
csv2 = f'his_ref,surgery_at,ot_code,patient_uhid,patient_name,procedure_name\nCSV-1,{TOM} 16:00,OT1,UH3001,Kiran Joshi,Laparotomy\n'
r = post(A, '/app/integrations/import', {'kind': 'surgeries'}, '/app/integrations/import', files={'file': ('s.csv', csv2, 'text/csv')})
check('1 surgeries saved' in r.text and sql(f"SELECT procedure_id IS NOT NULL FROM {DB}.surgeries WHERE his_ref='CSV-1'") == '1', 'CSV OT schedule import maps procedure by name')
r = get(A, '/app/integrations/log')
check('HL7' in r.text and 'FHIR' in r.text and 'WEBHOOK' in r.text and 'SSO' in r.text and 'CSV' in r.text, 'integration log shows every channel')
check('SIU^S12' in get(A, '/app/integrations/docs').text, 'API docs page')
check(get(T, '/app/integrations').status_code == 403, 'technician cannot open integrations (403)')
post(L1, f'/admin/tenants/{tid}', {'name': 'Integration Hospital', 'status': 'active', 'deployment': 'cloud', 'his_type': 'caresoft', 'country': 'India', 'valid_till': '2027-12-31'}, f'/admin/tenants/{tid}')
r = requests.get(B + '/api/v1/ping', headers=H)
check(r.status_code == 403 and 'not enabled' in r.text, 'Level 1 switches HIS integration off → API 403')
post(A, '/app/integrations/keys/1/revoke', {}, '/app/integrations')
print(f'\n{ok} passed, {bad} failed'); sys.exit(1 if bad else 0)
