#fcb2414b-067b-4ca2-91b2-6c36a86d4cbb = Vladimir Buzalka
#0210db7b-8fb0-4b47-b1d8-ec7a10849a63 = Vladko - testovací aplikace

#tento kód otevře pacienta podle jeho UUID a založí mu požadavek chřipka a finito

from pathlib import Path
from datetime import datetime
from playwright.sync_api import sync_playwright, TimeoutError as PWTimeout
import time

STATE_FILE = Path("../medevio_storage.json")
PATIENT_UUID = "0210db7b-8fb0-4b47-b1d8-ec7a10849a63"
PATIENT_URL = f"https://my.medevio.cz/mudr-buzalkova/klinika/pacienti?pacient={PATIENT_UUID}"
MESSAGE_TEXT = "Dobrý den, vakcína proti chřipce je k dispozici, zítra (úterý 23.9) budeme očkovat od 13-17 hodin, prosím potvrďte jestli můžete přijít a jaký čas se Vám hodí."

def savepage(name: str, page):
    """
    Save the current HTML of a Playwright Page to
    U:\Dropbox\!!!Days\Downloads Z230\Pages\<name>.html
    """
    folder = Path(r"U:\Dropbox\!!!Days\Downloads Z230\Pages")
    folder.mkdir(parents=True, exist_ok=True)  # ensure the folder exists

    # create sortable timestamp like 2025-09-19_14-05-33
    ts = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")

    filepath = folder / f"{ts}_{name}.html"
    with filepath.open("w", encoding="utf-8") as f:
        f.write(page.content())
    print(f"Saved page snapshot to {filepath}")

def main():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=200)
        context = browser.new_context(storage_state=str(STATE_FILE))

        # ---- keep a stable reference to the patient card page ----
        ptcard = context.new_page()
        ptcard.goto(PATIENT_URL, wait_until="networkidle")
        #saving ptcard1
        # savepage("ptcard1",ptcard)

        ptcard.get_by_text("Historie požadavků").wait_for(timeout=15_000)

        # 1) Create new request on the patient card
        ptcard.get_by_role("button", name="Nový požadavek").click()
        ptcard.wait_for_timeout(300)  # small settle

        # cursor is already in the "Začněte psát…" field
        ptcard.keyboard.type("očkování - chřipka")
        ptcard.locator("[role='option']", has_text="Očkování - Chřipka").first.click()
        ptcard.get_by_role("button", name="Vytvořit požadavek").click()

        #saving ptcard1
        # savepage("ptcard2",ptcard)

        # 2) Ensure we are back on the patient card again
        # (some UIs rerender; either way we want a fresh list)
        try:
            ptcard.get_by_text("Historie požadavků").wait_for(timeout=7_000)
        except PWTimeout:
            # If for any reason we are not on the card, navigate back explicitly
            ptcard.goto(PATIENT_URL, wait_until="networkidle")
            ptcard.get_by_text("Historie požadavků").wait_for(timeout=10_000)

        # Optional: hard refresh to get the just-created request at the top
        ptcard.reload(wait_until="networkidle")
        ptcard.get_by_text("Historie požadavků").wait_for(timeout=10_000)
        time.sleep(5)

        # 3) Open the “Očkování – Chřipka …” request card by its H4 text
        #    (click the whole card container, not just the heading)
        try:
            # wait until at least one request card is rendered
            ptcard.locator("div[data-testid='patient-request-item']").first.wait_for(timeout=10_000)

            # locate the specific card that contains the H4 with "Očkování - Chřipka"
            chripka_card = ptcard.locator("div[data-testid='patient-request-item']").filter(
                has=ptcard.locator("h4:has-text('Očkování - Chřipka')")
            ).first

            # ensure it's attached/visible then click it
            chripka_card.wait_for(timeout=10_000)
            chripka_card.click(timeout=5_000)

        except Exception as e:
            # Fallback: click the very first card on the list (newest)
            try:
                first_card = ptcard.locator("div[data-testid='patient-request-item']").first
                first_card.click(timeout=5_000)
            except Exception:
                # if even that fails, save snapshot for inspection and raise
                savepage("ptcard_click_fail", ptcard)
                raise

        # 4) Wait for request detail and send the message
        # We’re now on the detail page
        try:
            ptcard.wait_for_url("**/pozadavky?pozadavek=*", timeout=10_000)
        except PWTimeout:
            pass  # URL may be SPA; rely on textarea presence

        ptcard.get_by_placeholder("Napište odpověď").wait_for(timeout=10_000)
        ptcard.get_by_placeholder("Napište odpověď").fill(MESSAGE_TEXT)

        sent = False
        for sel in ["button:has-text('Odeslat')",
                    "button:has-text('Odeslat zprávu')",
                    "button:has-text('Odeslat SMS')",
                    "button:has-text('Odeslat do aplikace')"]:
            try:
                ptcard.click(sel, timeout=4000)
                sent = True
                break
            except Exception:
                continue

        if not sent:
            raise RuntimeError("Nepodařilo se najít/kliknout tlačítko Odeslat.")

        ptcard.wait_for_timeout(2000)
        print("✅ Požadavek vytvořen, otevřen a zpráva odeslána.")

if __name__ == "__main__":
    main()
