import os.path
from pathlib import Path

import h5py
from silx.io.url import DataUrl

from ..bliss_globals import current_session
from ..processor import BlissScanType
from ..utils.directories import get_filename


def export_filename_prefix(scan: BlissScanType, lima_name: str) -> str:
    scan_filename = Path(get_filename(scan))
    scan_nb = scan.scan_info.get("scan_nb")
    return f"{scan_filename.stem}_s{scan_nb:04d}_{lima_name}"


def get_current_filename() -> str:
    return current_session.scan_saving.filename


def subtracted_nxprocess_name(lima_name: str) -> str:
    return f"{lima_name}_integrate_subtracted"


def assert_url_exists(url: str) -> None:
    data_url = DataUrl(url)
    if not os.path.exists(data_url.file_path()):
        raise FileNotFoundError(f"{data_url.file_path()} does not exist")

    with h5py.File(data_url.file_path(), "r") as h5file:
        if data_url.data_path() not in h5file:
            raise FileNotFoundError(
                f"{data_url.data_path()} does not exist in {data_url.file_path()}"
            )
