from playwright.sync_api import sync_playwright
import os
import datetime

# ── CONFIG ──────────────────────────────────────────────────────────────────
BASE_URL = "https://janssen.4gclinical.com"
EMAIL    = "vbuzalka@its.jnj.com"
PASSWORD = "Vlado123++-+"

STUDIES = ["77242113UCO3001", "42847922MDD3003"]

BASE_DIR     = os.path.dirname(os.path.abspath(__file__))
INCOMING_DIR = os.path.join(BASE_DIR, "IncomingSourceReports")
CREATED_DIR  = os.path.join(BASE_DIR, "CreatedReports")
# ────────────────────────────────────────────────────────────────────────────


def unique_path(directory, stem):
    path = os.path.join(directory, f"{stem}.xlsx")
    if not os.path.exists(path):
        return path
    time_tag = datetime.datetime.now().strftime("%H%M")
    return os.path.join(directory, f"{stem} {time_tag}.xlsx")


def download_study(page, study, today):
    print(f"\n[{study}] Prihlaseni...")
    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")

    print(f"[{study}] Vyber studie...")
    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")

    print(f"[{study}] Stahuji Subject Summary Report...")
    page.goto(f"{BASE_URL}/report/patient_summary_report")
    page.wait_for_load_state("networkidle", timeout=120000)

    filename = unique_path(INCOMING_DIR, f"{today} {study} Subject Summary Report")
    with page.expect_download(timeout=120000) as dl:
        page.get_by_role("button", name="Download XLS").click()
    dl.value.save_as(filename)
    print(f"[{study}] OK -> {filename}")
    return filename


def main():
    today = datetime.date.today().strftime("%Y-%m-%d")
    os.makedirs(INCOMING_DIR, exist_ok=True)
    os.makedirs(CREATED_DIR, exist_ok=True)

    downloaded = []

    with sync_playwright() as p:
        for study in STUDIES:
            browser = p.chromium.launch(headless=False)
            context = browser.new_context(accept_downloads=True)
            page = context.new_page()

            filename = download_study(page, study, today)
            downloaded.append((study, filename))

            browser.close()

    print("\nVse stazeno:")
    for study, path in downloaded:
        print(f"  {study}: {path}")


main()
