import time
from playwright.sync_api import sync_playwright
import mysql.connector

MYSQL_CFG = dict(
    host="192.168.1.76",
    port=3307,
    user="root",
    password="Vlado9674+",
    database="medevio",
)

# --- load 3 patients from DB ---
conn = mysql.connector.connect(**MYSQL_CFG)
with conn.cursor() as cur:
    cur.execute("""
        SELECT rid, prijmeni, jmeno, rc
        FROM patients_extracted
        WHERE prijmeni IS NOT NULL and mamedevioucet is  null
        ORDER BY prijmeni ASC
        LIMIT 300
    """)
    rows = cur.fetchall()
    if not rows:
        raise RuntimeError("No entries found in patients_extracted")

STATE_FILE = r"medevio_storage.json"
BASE_URL   = "https://my.medevio.cz/mudr-buzalkova/klinika/pacienti"

NOT_FOUND_SEL = "div[role='alert']:has-text('Pacient nebyl nalezen'), div:has-text('Pacient nebyl nalezen')"
DIALOG_SEL    = "[role='dialog'], div.MuiDrawer-paper, div[aria-modal='true']"

def close_dialog_if_open(page):
    dlg = page.locator(DIALOG_SEL)
    try:
        if dlg.count():
            # Try a close button; if not, press Escape
            try:
                dlg.locator("button:has-text('Zavřít'), [aria-label='Zavřít'], [aria-label='Close'], [data-testid='CloseIcon']").first.click(timeout=1000)
            except:
                page.keyboard.press("Escape")
            page.wait_for_selector(DIALOG_SEL, state="detached", timeout=1500)
    except:
        pass  # best-effort close

def main():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context(storage_state=STATE_FILE)
        page = context.new_page()

        for rid, surname, name, rc in rows:
            print(f"\nProcessing {surname} {name} {rc}")

            # 1️⃣ Navigation time
            t0 = time.perf_counter()
            page.goto(f"{BASE_URL}?pacient={rid}", wait_until="domcontentloaded")
            # page.wait_for_load_state("networkidle")
            t_nav = time.perf_counter() - t0
            print(f"  ⏱️ page.goto + networkidle: {t_nav:.2f}s")

            # 2️⃣ Toast / dialog detection
            t1 = time.perf_counter()
            not_found = False
            try:
                page.wait_for_selector(NOT_FOUND_SEL, timeout=2500)
                not_found = True
            except:
                pass
            if not_found:
                print(f"  ⚠️ not-found toast detected after {time.perf_counter() - t1:.2f}s")
                continue

            try:
                page.wait_for_selector(DIALOG_SEL, timeout=8000)
            except:
                print(f"  ⚠️ dialog not found (waited {time.perf_counter() - t1:.2f}s)")
                continue
            t_dialog = time.perf_counter() - t1
            print(f"  ⏱️ toast/dialog detection: {t_dialog:.2f}s")

            # 3️⃣ Account check + DB update
            t2 = time.perf_counter()
            text = page.locator(DIALOG_SEL).first.inner_text()
            has_account = 0 if "zatím nemá Medevio účet" in text else 1
            with conn.cursor() as c:
                c.execute("UPDATE patients_extracted SET mamedevioucet=%s WHERE rid=%s",
                          (has_account, rid))
            conn.commit()
            t_db = time.perf_counter() - t2
            print(f"  ⏱️ DB update & text parse: {t_db:.2f}s")

            # 4️⃣ Optional pacing
            t3 = time.perf_counter()
            # time.sleep(0.5)
            print(f"  ⏱️ explicit sleep: {time.perf_counter() - t3:.2f}s")

        browser.close()

if __name__ == "__main__":
    main()
