from playwright.sync_api import sync_playwright
import os

# ── CONFIG ──────────────────────────────────────────────────────────────────
BASE_URL = "https://janssen.4gclinical.com"

EMAIL    = "vbuzalka@its.jnj.com"
PASSWORD = "Vlado123++-+"

# STUDY = "42847922MDD3003"
STUDY = "77242113UCO3001"

OUTPUT_DIR = f"xls_shipments_{STUDY}"
# ────────────────────────────────────────────────────────────────────────────

def run(page, study):
    output_dir = f"xls_shipments_{study}"
    os.makedirs(output_dir, exist_ok=True)

    page.goto(f"{BASE_URL}/report/shipments_report")
    page.wait_for_load_state("networkidle", timeout=120000)

    filename = os.path.join(output_dir, f"shipments_report_{study}.xlsx")
    with page.expect_download(timeout=120000) as dl:
        page.get_by_role("button", name="Download XLS").click()
    dl.value.save_as(filename)
    print(f"  Shipments report OK -> {filename}")


if __name__ == "__main__":
    from playwright.sync_api import sync_playwright
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        context = browser.new_context(accept_downloads=True)
        page = context.new_page()
        page.goto(BASE_URL)
        page.wait_for_load_state("networkidle")
        page.get_by_label("Email *").fill(EMAIL)
        page.get_by_label("Password *").fill(PASSWORD)
        page.locator('#login__submit').click()
        page.wait_for_load_state("networkidle")
        page.get_by_label("Study *").click()
        page.get_by_role("option", name=STUDY).click()
        page.get_by_role("button", name="SELECT").click()
        page.wait_for_load_state("networkidle")
        run(page, STUDY)
        browser.close()
