import sys
import os
from playwright.sync_api import sync_playwright

import download_reports
import download_ip_destruction
import download_shipments_report
import download_shipment_details
import create_accountability_report

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

STUDIES = {
    "1": "77242113UCO3001",
    "2": "42847922MDD3003",
}


def pick_study():
    print("Vyber studii:")
    for k, v in STUDIES.items():
        print(f"  {k}) {v}")
    while True:
        choice = input("Volba (1/2): ").strip()
        if choice in STUDIES:
            return STUDIES[choice]
        print("  Neplatna volba, zkus znovu.")


def login_and_select_study(page, study):
    print(f"\n[1/5] Prihlaseni a vyber studie {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")
    print("  OK")


def main():
    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    study = pick_study()

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

        login_and_select_study(page, study)

        print(f"\n[2/5] Stahuji inventory reporty...")
        download_reports.run(page, study)

        print(f"\n[3/5] Stahuji IP destruction reporty...")
        download_ip_destruction.run(page, study)

        print(f"\n[4/5] Stahuji shipments report...")
        download_shipments_report.run(page, study)

        print(f"\n[5/5] Stahuji shipment details...")
        download_shipment_details.run(page, study)

        browser.close()

    print(f"\n[6/6] Generuji accountability report...")
    create_accountability_report.STUDY          = study
    create_accountability_report.INVENTORY_DIR  = __import__("pathlib").Path(f"xls_reports_{study}")
    create_accountability_report.DESTRUCTION_DIR= __import__("pathlib").Path(f"xls_ip_destruction_{study}")
    create_accountability_report.SHIPMENTS_FILE = __import__("pathlib").Path(f"xls_shipments_{study}/shipments_report_{study}.xlsx")
    create_accountability_report.DETAILS_DIR    = __import__("pathlib").Path(f"xls_shipment_details_{study}")
    create_accountability_report.OUTPUT_FILE    = create_accountability_report.OUTPUT_DIR / f"{__import__('datetime').date.today().strftime('%Y-%m-%d')} {study} CZ IWRS overview.xlsx"
    create_accountability_report.main()

    print("\nVse hotovo!")


main()
