# Phase 5 end-to-end: demo hospital generator, reports engine, KPI dashboard, wall board, L1 demo reset, marketing content.
import os, re, sys, json, 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 sql(q): return subprocess.run(['mysql', '-uroot', '-N', '-e', q], capture_output=True, text=True).stdout.strip()
def err(t): return re.search(r'(Warning|Fatal error|Deprecated|Notice)\b[^<]{0,3}:', t)
DB = 'cssd_demo'
TZ = subprocess.run(['php', '-r', 'require "' + ROOT + '/app/bootstrap.php"; echo date("P");'], capture_output=True, text=True).stdout.strip()
sql("DELETE FROM cssd_control.login_attempts")

print('Demo hospital generator')
out = subprocess.run(['php', ROOT + '/install/demo_data.php', '--days=30'], capture_output=True, text=True).stdout
check('30 days of history' in out and 'supervisor' in out, 'CLI builds DEMO with 30 days and prints the user list')
n = lambda q: int(sql(q) or 0)
check(n(f"SELECT COUNT(*) FROM {DB}.cycles") > 800, 'hundreds of pack cycles generated')
check(n(f"SELECT COUNT(*) FROM {DB}.sterilizer_loads WHERE status='failed'") >= 1, 'at least one failed load (quarantine + reprocess path)')
check(n(f"SELECT COUNT(*) FROM {DB}.cycles WHERE close_reason='failed_load'") >= 1, 'failed-load packs closed and reprocessed')
check(n(f"SELECT COUNT(*) FROM {DB}.recalls WHERE status='closed' AND trigger_source='bi_positive'") == 1, 'closed BI-positive recall with items')
check(n(f"SELECT COUNT(*) FROM {DB}.recall_items") >= 1, 'recall lines created')
check(n(f"SELECT COUNT(*) FROM (SELECT set_unit_id FROM {DB}.cycles WHERE status<>'closed' GROUP BY set_unit_id HAVING COUNT(*)>1) x") == 0, 'never more than one open cycle per set unit')
check(n(f"SELECT COUNT(*) FROM {DB}.cycles c JOIN {DB}.sterilizer_loads l ON l.id=c.load_id WHERE c.status IN ('in_store','issued','used') AND l.status<>'released'") == 0, 'every pack in store / issued / used came from a released load')
check(n(f"SELECT COUNT(*) FROM {DB}.cycles WHERE status='used' AND patient_uhid IS NULL") == 0, 'every used pack linked to a patient')
check(n(f"SET time_zone = '{TZ}'; SELECT COUNT(*) FROM {DB}.cycles WHERE received_at > NOW() OR released_at > NOW() OR issued_at > NOW()") == 0, 'no timestamps in the future')
check(n(f"SELECT next_val FROM {DB}.sequences WHERE name='pack'") > n(f"SELECT COUNT(*) FROM {DB}.cycles WHERE pack_no IS NOT NULL"), 'pack sequence continues after generated numbers')
check(n(f"SELECT COUNT(*) FROM {DB}.cycles WHERE cost IS NULL AND status IN ('in_store','issued','used')") == 0, 'cost frozen on every released pack')
check(n(f"SELECT COUNT(*) FROM {DB}.charges") > 50, 'patient charges generated')
check(n(f"SELECT COUNT(*) FROM {DB}.machine_tests WHERE test_type='bowie_dick' AND result='fail'") >= 0, 'Bowie-Dick history present')

print('Demo logins')
SUP = requests.Session()
r = post(SUP, '/login', {'mode': 'password', 'client_code': 'DEMO', 'username': 'supervisor', 'password': 'Demo#2026'}, '/login')
check('/app' in r.url and 'Sunita Rao' in r.text, 'supervisor logs in with the demo password (no forced change)')
TECH = requests.Session()
r = post(TECH, '/login', {'mode': 'pin', 'client_code': 'DEMO', 'username': 'tech1', 'pin': '1234'}, '/login')
check('/app' in r.url and 'Ravi Patil' in r.text, 'technician logs in with the demo floor PIN')

print('KPI dashboard')
r = get(SUP, '/app/kpi?p=30')
check(r.status_code == 200 and not err(r.text), 'KPI page renders without warnings')
check(len(re.findall(r'class="card kpi', r.text)) == 12, '12 KPI cards for a role with cost access')
check(r.text.count('<svg class="chart"') == 4 and 'class="sr-only"' in r.text, '4 server-side SVG charts with accessible data tables')
check('Off target' in r.text or 'On target' in r.text, 'targets compared')
for p in ['7', '90', 'month', 'lastmonth', 'custom&from=2026-01-01&to=2026-12-31', 'bogus']:
    rr = get(SUP, '/app/kpi?p=' + p); check(rr.status_code == 200 and not err(rr.text), f'period preset {p.split("&")[0]} works')
r = get(SUP, '/app/kpi?p=30&print=1')
check('window.print()' in r.text and 'class="side"' not in r.text, 'print view is standalone')
r = get(TECH, '/app/kpi')
check(r.status_code == 403, 'technician (no report rights) blocked from KPIs')
check('KPI dashboard' not in get(TECH, '/app').text and 'CSSD wall board' in get(TECH, '/app').text, 'menu: KPI hidden for technician, wall board shown')
MG = requests.Session(); post(MG, '/login', {'mode': 'password', 'client_code': 'DEMO', 'username': 'mgmt', 'password': 'Demo#2026'}, '/login')
check(get(MG, '/app/kpi').status_code == 200, 'management (view only) sees KPIs')

print('Reports engine')
keys = sorted(set(re.findall(r'/app/registers/([a-z0-9_]+)"', get(SUP, '/app/registers').text)))
check(len(keys) >= 45, f'{len(keys)} reports listed for supervisor')
bad_r = [k for k in keys if (lambda x: x.status_code != 200 or err(x.text))(get(SUP, f'/app/registers/{k}?from=2026-01-01&to=2026-12-31'))]
check(not bad_r, 'every report runs on demo data' + (f' — failed: {bad_r}' if bad_r else ''))
csv = get(SUP, f'/app/registers/{keys[0]}?export=csv&from=2026-01-01&to=2026-12-31')
check(csv.headers.get('content-type', '').startswith('text/csv'), 'CSV export works')

print('Wall board')
r = get(TECH, '/app/board')
check(r.status_code == 200 and 'Sterile in store' in r.text and 'setInterval' in r.text, 'logged-in board renders with auto refresh')
r = get(TECH, '/app/board?part=1')
check(r.status_code == 200 and '<html' not in r.text and 'Running loads' in r.text, 'refresh endpoint returns the board fragment only')
check(get(requests.Session(), '/app/board').url.endswith('/login'), 'board needs login without the token link')
ADM = requests.Session()
post(ADM, '/login', {'mode': 'password', 'client_code': 'DEMO', 'username': 'admin', 'password': 'Demo#2026'}, '/login'); post(ADM, '/login/otp', {'code': otp()})
h = get(ADM, '/app/settings').text
link = re.search(r'value="(http[^"]+/board/DEMO/[0-9a-f]{64})"', h)
check(bool(link), 'hospital admin sees the TV link in settings')
link = link.group(1)
pub = requests.get(link)
check(pub.status_code == 200 and 'Sterile in store' in pub.text and pub.headers.get('X-Robots-Tag', '').startswith('noindex'), 'token link works without login, noindex')
check(not re.search(r'UH\d{6}', pub.text), 'board shows no patient identifiers')
check(requests.get(link + '?part=1').status_code == 200, 'token refresh endpoint works')
check(requests.get(link[:-2] + 'ff').status_code == 404 and requests.get(B + '/board/DEMO/abc').status_code == 404, 'wrong token → 404')
other = sql("SELECT client_code FROM cssd_control.tenants WHERE client_code<>'DEMO' LIMIT 1")
if other: check(requests.get(link.replace('/DEMO/', f'/{other}/')).status_code == 404, 'token of one hospital does not open another')
post(ADM, '/app/board/token', {}, '/app/settings')
check(requests.get(link).status_code == 404, 'regenerated link — old link stops working')
new = re.search(r'value="(http[^"]+/board/DEMO/[0-9a-f]{64})"', get(ADM, '/app/settings').text).group(1)
check(new != link and requests.get(new).status_code == 200, 'new link works')
check(n(f"SELECT COUNT(*) FROM {DB}.audit_log WHERE action='regenerated' AND entity='board_link'") == 1, 'link change audited')

print('KPI targets in settings')
cur = dict(re.findall(r'name="(\w+)" value="([^"]*)"', get(ADM, '/app/settings').text))
cur.pop('_csrf', None)
cur.update({'kpi_target_tat_pct': '50', 'kpi_target_fail_pct': '150'})
post(ADM, '/app/settings', cur, '/app/settings')
check(sql(f"SELECT value FROM {DB}.settings WHERE `key`='kpi_target_tat_pct'") == '50', 'target saved')
check(sql(f"SELECT value FROM {DB}.settings WHERE `key`='kpi_target_fail_pct'") == '1', 'out-of-range target (150%) rejected')
check('target ≥ 50%' in get(SUP, '/app/kpi?p=30').text, 'KPI card uses the new target')

print('Level 1 demo reset')
L1 = requests.Session()
post(L1, '/admin/login', {'email': 'superadmin@example.com', 'password': 'Admin#2026x'}); post(L1, '/admin/otp', {'code': otp()})
did = sql("SELECT id FROM cssd_control.tenants WHERE client_code='DEMO'")
check('Rebuild demo data' in get(L1, f'/admin/tenants/{did}').text, 'demo client shows the rebuild button')
if other:
    oid = sql(f"SELECT id FROM cssd_control.tenants WHERE client_code='{other}'")
    check('Rebuild demo data' not in get(L1, f'/admin/tenants/{oid}').text, 'non-demo client has no rebuild button')
    check(post(L1, f'/admin/tenants/{oid}/demo-reset', {'confirm': other, 'days': '30'}, f'/admin/tenants/{oid}').status_code == 403, 'non-demo client cannot be wiped')
r = post(L1, f'/admin/tenants/{did}/demo-reset', {'confirm': 'WRONG', 'days': '30'}, f'/admin/tenants/{did}')
check('Type the client code' in r.text, 'wrong confirmation refused')
r = post(L1, f'/admin/tenants/{did}/demo-reset', {'confirm': 'demo', 'days': '30'}, f'/admin/tenants/{did}')
check('Demo data rebuilt' in r.text, 'rebuild succeeds from Level 1')
check(n("SELECT COUNT(*) FROM cssd_control.platform_audit WHERE action='demo_reset'") >= 1, 'rebuild audited')
check(n(f"SELECT COUNT(*) FROM {DB}.audit_log WHERE action='regenerated'") == 0, 'old data gone after rebuild')

print('Marketing content')
sm = requests.get(B + '/sitemap.xml').text
urls = re.findall(r'<loc>([^<]+)</loc>', sm)
check(len(urls) >= 30, f'sitemap lists {len(urls)} URLs')
broken = [u for u in urls if requests.get(u).status_code != 200]
check(not broken, 'every sitemap URL returns 200')
g = requests.get(B + '/cssd-glossary').text
check('"DefinedTermSet"' in g and g.count('"DefinedTerm"') >= 30, 'glossary has DefinedTermSet schema with 30+ terms')
r = requests.get(B + '/cssd-roi-calculator').text
check('id="r_total"' in r and 'not a guarantee' in r, 'ROI calculator with stated assumptions')
for s in ['cssd-software-uae', 'cssd-software-saudi-arabia', 'cssd-software-kenya', 'cssd-software-nigeria']:
    t = requests.get(B + '/' + s).text
    check('"BreadcrumbList"' in t and 'name="country"' in t or 'country' in t, f'{s} renders with breadcrumb and lead form')
check('CBAHI' in requests.get(B + '/cssd-software-saudi-arabia').text, 'Saudi page mentions CBAHI')
t = requests.get(B + '/resources/bowie-dick-test-guide').text
check('"HowTo"' in t and '"Article"' in t, 'new guide carries Article + HowTo schema')
l = requests.get(B + '/llms.txt').text
check('ROI calculator' in l and 'Saudi Arabia' in l and 'wall board' in l, 'llms.txt lists new pages, regions and analytics')

print(f'\n{ok} passed, {bad} failed')
sys.exit(1 if bad else 0)
