"""
download_patients.py — stažení pacientských reportů pro jednu studii.
Verze: 1.1 | Datum: 2026-06-10
  v1.1: přesun na úroveň IWRS/

Volá se z IWRS/run_all_v1.1.py s již přihlášenou Playwright page (login +
výběr studie zajišťuje common.iwrs_portal.login).

  1. Subject Summary Report
  2. Subject Detail Reports + notifikace PDF+JSON (per subjekt, jen nové dle pk v Mongo)

Vše se ukládá ploše do IWRS/Incoming/ s datumovanými názvy.
"""

import os
import sys
import datetime

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
if BASE_DIR not in sys.path:
    sys.path.insert(0, BASE_DIR)

from common.iwrs_portal import BASE_URL
from common.paths import INCOMING_DIR, unique_path

import download_subject_details as dsd


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 run(page, study):
    """Stáhne summary + detaily + notifikace pro studii do IWRS/Incoming/."""
    os.makedirs(INCOMING_DIR, exist_ok=True)
    today = datetime.date.today().strftime("%Y-%m-%d")
    download_summary(page, study, today)
    # detail XLSX + notifikace přímo do Incoming/ (flat názvy se study+subject)
    dsd.run(page, study, out_dir=INCOMING_DIR, subjects_source_dir=INCOMING_DIR)
