import re, time, hmac, hashlib, base64, struct, subprocess
from playwright.sync_api import sync_playwright
B="http://localhost:8080"
def totp(secret):
    key=base64.b32decode(secret+"="*(-len(secret)%8)); msg=struct.pack(">Q",int(time.time())//30)
    h=hmac.new(key,msg,hashlib.sha1).digest(); o=h[19]&15
    return "%06d"%((struct.unpack(">I",h[o:o+4])[0]&0x7fffffff)%1000000)
q=lambda s, db="cp_client_demo": subprocess.check_output(["mysql","-uroot","-N",db,"-e",s]).decode().strip()
with sync_playwright() as p:
    br=p.chromium.launch(channel="chrome", args=["--no-sandbox"])
    pg=br.new_page(viewport={"width":1440,"height":900})
    pg.goto(B+"/login"); pg.fill("[name=client_code]","DEMO"); pg.fill("[name=email]","admin@demo.demo"); pg.fill("[name=password]","Demo@12345"); pg.click("button")
    if "Set up" in pg.content():
        sec=re.search(r'class="code">([A-Z2-7 ]+)<', pg.content()).group(1).replace(" ","")
        pg.fill("[name=code]", totp(sec)); pg.click("button")
    else:
        pg.fill("[name=code]", totp(q("SELECT totp_secret FROM users WHERE email='admin@demo.demo'"))); pg.click("button")
    fl=q("SELECT id FROM floors LIMIT 1"); inv=q("SELECT id FROM invoices WHERE status='paid' LIMIT 1","carepulse_central")
    for name,path,full in [("p4_floor_map",f"/floors/{fl}",False),("p4_floor_edit",f"/floors/{fl}/edit",False),("p4_nurse_call","/nurse-calls",False),("p4_utilities","/utilities",True),
                           ("p4_maintenance","/maintenance",False),("p4_uptime","/maintenance/uptime?from=2026-10-01",False),("p4_analytics","/analytics",True),("p4_billing","/billing",False),
                           ("p4_invoice",f"/billing/{inv}",True),("p4_tags","/tags",False),("p4_wo","/maintenance/2",False)]:
        pg.goto(B+path); pg.wait_for_timeout(2500); pg.screenshot(path=f"shots/{name}.png", full_page=full)
    br.close()
print("ok")
