"""Code for parsing data generated by a Tecan Sunrise platereader."""

import itertools

import numpy as np
import pandas as pd


def parseSunrise(dfd: pd.DataFrame, rdict: dict[str, list[float | str]]):
    """Parse a data frame from a Sunrise plate reader into a dict."""
    rdict["OD"] = []
    # extract times of measurements
    t = (
        np.array([float(str(ts).split("s")[0]) for ts in dfd.to_numpy()[0]])
        / 3600
    )
    t = t[~np.isnan(t)]
    # add well positions to dfd
    mask = pd.to_numeric(dfd[dfd.columns[-1]], errors="coerce").notna()
    dfd["well_positions"] = None
    value_iter = itertools.cycle(
        [
            f"{letter}{number}"
            for letter in "ABCDEFGH"
            for number in range(1, 13)
        ]
    )
    dfd.loc[mask, "well_positions"] = [
        next(value_iter) for _ in range(mask.sum())
    ]
    # extract data
    for x in np.arange(1, 13):
        for y in "ABCDEFGH":
            well = y + str(x)
            if well in dfd["well_positions"].values:
                data = dfd[dfd["well_positions"] == well].iloc[:, :-1].values
                data = data.reshape(data.size)
                for i, tv in enumerate(t):
                    rdict["time"].append(tv)
                    rdict["well"].append(well)
                    rdict["OD"].append(data[i])
    return rdict
