"""
Stažení reportů z IWRS portálu — vše do jednoho adresáře `Incoming/`.

  1. Subject Summary Report (per studie)
  2. Subject Detail Reports + notifikace (per subjekt)

Import se spouští samostatně skriptem `import_all.py`.
"""

import os
import datetime

from playwright.sync_api import sync_playwright

import download_subject_details as dsd

# ── 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, "Incoming")


def unique_path(directory, stem, ext=".xlsx"):
    path = os.path.join(directory, f"{stem}{ext}")
    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}{ext}")


def login(page, study):
    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")


def download_summary(page, study, today):
    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}] Summary OK -> {os.path.basename(filename)}")
    return filename


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

    with sync_playwright() as p:
        for study in STUDIES:
            print("\n" + "=" * 60)
            print(f"[{study}] Stažení reportů")
            print("=" * 60)
            browser = p.chromium.launch(headless=False)
            context = browser.new_context(accept_downloads=True)
            page = context.new_page()
            try:
                login(page, study)
                download_summary(page, study, today)
                # detail XLSX + notifikace přímo do Incoming/
                dsd.run(page, study, out_dir=INCOMING_DIR, subjects_source_dir=INCOMING_DIR)
            except Exception as e:
                print(f"  [{study}] CHYBA: {e}")
            finally:
                browser.close()

    print("\n" + "=" * 60)
    print(f"Stahování hotovo. Soubory v: {INCOMING_DIR}")
    print("Pro import spusť: python import_all.py")
    print("=" * 60)


if __name__ == "__main__":
    main()
