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

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 3
    """)
    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)
        try:
            context = browser.new_context(storage_state=STATE_FILE)
            page = context.new_page()

            for rid, surname, name, rc in rows:
                # 0) close any previous dialog to avoid stale matches
                close_dialog_if_open(page)

                target_url = f"{BASE_URL}?pacient={rid}"
                page.goto(target_url, wait_until="domcontentloaded")
                page.wait_for_load_state("networkidle")

                # 1) Not-found toast?
                try:
                    page.wait_for_selector(NOT_FOUND_SEL, timeout=3000)
                    print(f"{surname} {name} {rc} – ⚠️ pacient s RID {rid} nebyl nalezen, přeskočeno")
                    # (optional) set mamedevioucet=NULL for this rid here
                    continue
                except:
                    pass

                # 2) Detail panel
                try:
                    page.wait_for_selector(DIALOG_SEL, timeout=6000)
                except:
                    print(f"⚠️ {surname} {name} {rc}: detailový panel se nenačetl, přeskočeno")
                    continue

                # 3) Verify dialog belongs to current patient (avoid stale dialog)
                detail = page.locator(DIALOG_SEL).first
                detail_text = detail.inner_text()

                if (surname not in detail_text) and (rc not in detail_text):
                    # Still looks wrong; give UI a moment and re-check once
                    page.wait_for_timeout(500)
                    detail_text = detail.inner_text()
                    if (surname not in detail_text) and (rc not in detail_text):
                        print(f"⚠️ {surname} {name} {rc}: detail neodpovídá (stará karta?), přeskočeno")
                        continue

                # 4) Check Medevio account text
                if "zatím nemá Medevio účet" in detail_text:
                    has_account = 0
                    print(f"{surname} {name} {rc} – ❌ zatím nemá Medevio účet")
                else:
                    has_account = 1
                    print(f"{surname} {name} {rc} – ✅ má Medevio účet")

                # Update DB by RID (or swap to rc if you prefer)
                with conn.cursor() as c:
                    c.execute(
                        "UPDATE patients_extracted SET mamedevioucet = %s WHERE rid = %s",
                        (has_account, rid),
                    )
                conn.commit()

                time.sleep(0.5)  # gentle pacing

        finally:
            browser.close()

if __name__ == "__main__":
    main()
