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"

SITES = {
    "42847922MDD3003": [
        "S10-CZ10002",
        "S10-CZ10004",
        "S10-CZ10005",
        "S10-CZ10008",
        "S10-CZ10011",
        "S10-CZ10012",
    ],
    "77242113UCO3001": [
        "DD5-CZ10001",
        "DD5-CZ10003",
        "DD5-CZ10006",
        "DD5-CZ10009",
        "DD5-CZ10010",
        "DD5-CZ10012",
        "DD5-CZ10013",
        "DD5-CZ10015",
        "DD5-CZ10016",
        "DD5-CZ10020",
        "DD5-CZ10021",
        "DD5-CZ10022",
    ],
}

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

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

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

    for site_id in SITES[study]:
        print(f"  [{site_id}] Stahuji...")
        page.locator('input[placeholder="search"], input[type="text"]').first.click()
        page.get_by_role("option", name=site_id).click()
        page.wait_for_load_state("networkidle", timeout=120000)

        with page.expect_download(timeout=120000) as dl:
            page.get_by_role("button", name="Download XLS").click()

        dl.value.save_as(os.path.join(output_dir, f"onsite_inventory_detail_{site_id}.xlsx"))
        print(f"  [{site_id}] OK")

        page.get_by_role("button", name="Clear").click()
        page.wait_for_load_state("networkidle", timeout=120000)

    print("  Inventory hotovo.")


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()
