# Název:  download_test_results_v1.0.py
# Verze:  1.0
# Datum:  2026-05-28
# Popis:  Stahuje Standard Test Results ze Covance/Labcorp XSP
#         pro studii 77242113UCO3001 (study 36940, report 930556).
#         Login přes xsp.covance.com → Okta, pak přímá URL na report.
#         Výstup: timestampované CSV do adresáře Source/.

from playwright.sync_api import sync_playwright
from datetime import datetime
import os

EMAIL       = "vbuzalka@its.jnj.com"
PASSWORD    = "%zT3Wqfc9)cWua5"
LOGIN_URL   = "https://xsp.covance.com/"
OUT_DIR     = r"U:\PythonProject\Janssen\Covance_UCO3001\Source"
PROFILE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "browser_profile")

REPORTS = [
    {
        "site":     "CZ10003",
        "url":      "https://xsp.labcorp.com/sponsor/study/36940/test-results/930556/standard-test-results",
        "filename": "sponsor-study-36940-test-results-930556-standard-test-results.csv",
    },
]


def login(page):
    page.goto(LOGIN_URL)
    page.wait_for_load_state("networkidle")
    page.get_by_label("Email").fill(EMAIL)
    page.get_by_role("button", name="Next").click()
    page.wait_for_load_state("networkidle")
    page.get_by_label("Password").fill(PASSWORD)
    page.get_by_role("button", name="Verify").click()
    page.wait_for_url(lambda url: "code=" not in url, timeout=60000)
    page.wait_for_load_state("networkidle", timeout=60000)
    page.wait_for_timeout(2000)
    print(f"Prihlaseni OK: {page.url}")


def download_report(page, report):
    print(f"\n--- {report['site']} ---")
    page.goto(report["url"])
    page.wait_for_load_state("networkidle", timeout=60000)
    page.wait_for_timeout(3000)
    print(f"Report nacteny: {page.url}")

    # Kliknout 3 tečky (more_horiz) vpravo od filtrovacího řádku
    page.locator("button").filter(has_text="more_horiz").last.click()

    timestamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")
    dest = os.path.join(OUT_DIR, f"{timestamp} {report['filename']}")

    with page.expect_download(timeout=60000) as dl:
        page.get_by_text("Export to CSV").click()

    dl.value.save_as(dest)
    print(f"Stazeno: {dest}")


if __name__ == "__main__":
    with sync_playwright() as p:
        context = p.chromium.launch_persistent_context(
            user_data_dir=PROFILE_DIR,
            headless=False,
            args=["--disable-blink-features=AutomationControlled", "--start-maximized"],
            no_viewport=True,
            user_agent=(
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                "AppleWebKit/537.36 (KHTML, like Gecko) "
                "Chrome/136.0.0.0 Safari/537.36"
            ),
            accept_downloads=True,
        )
        context.add_init_script(
            "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
        )
        page = context.new_page()
        login(page)
        for report in REPORTS:
            download_report(page, report)
        context.close()
