import csv
import typing as t
from pathlib import Path

from packaging import version
from zhinst.toolkit import Session, Waveforms


def _write_csv_file(lines: t.List, file: Path) -> None:
    """Write lines to a CSV file

    Args:
        lines: Lines to write.
        file: output file.
    """
    with file.open("w") as file:
        writer = csv.writer(
            file, delimiter=",", quotechar="|", quoting=csv.QUOTE_MINIMAL
        )
        for line in lines:
            writer.writerow(line)


def export_waveforms(waveforms: Waveforms, output_dir: Path) -> None:
    """Export a Waveform object to CSV.

    The file generated by this function can be used directly in the Labber
    drivers.

    The output format is a CSV with `,` as delimiters. Each line represents a
    waveform slot/index. If no waveform is present for a given index the
    resulting line will be empty.

    Args:
        waveforms: Waveforms to be exported.
        output_dir: Output directory for the csv files
    """
    max_key = max(list(waveforms.keys())) + 1
    wave_1 = [[]] * max_key
    wave_2 = [[]] * max_key
    markers = [[]] * max_key
    wave_2_present = False
    markers_present = False
    for key, wave in waveforms.items():
        wave_1[key] = wave[0]
        if wave[1] is not None:
            wave_2_present = True
            wave_2[key] = wave[1]
        if wave[2] is not None:
            markers_present = True
            markers[key] = wave[2]

    if not output_dir.exists():
        output_dir.mkdir()

    _write_csv_file(wave_1, output_dir / "wave1.csv")
    if wave_2_present:
        _write_csv_file(wave_2, output_dir / "wave2.csv")
    if markers_present:
        _write_csv_file(markers, output_dir / "markers.csv")


def check_compatibility(session: Session) -> None:
    """Check the compatibility of LabOne.

    Args:
        session: active toolkit session.
    Raised:
        RuntimeError: If LabOne is not compatible with the Labber driver.
    """
    LAST_SUPPORTED_VERSION = version.Version("24.10")
    try:
        current_version = version.Version(session.about.version())
    except Exception:
        current_version = LAST_SUPPORTED_VERSION
    if current_version > LAST_SUPPORTED_VERSION:
        raise RuntimeError(
            f"LabOne version {current_version} is not supported by the Labber driver. "
            f"Please use LabOne version {LAST_SUPPORTED_VERSION} or lower."
        )
