# pyright: basic
import plotly.express as px
import pandas as p
from datetime import datetime
from pathlib import Path

p.options.plotting.backend = "plotly"


SHIELD_CERNOX = "LS336 CHD[K]"
BOTTOM_SCREWED_CERNOX = "LS336 CHB[K]"
TOP_SCREWED_CERNOX = "LS336 CHA[K]"
BOTTOM_SAMPLE_CERNOX = "LS218 CH8[K]"
TOP_SAMPLE_CERNOX = "LS218 CH1[K]"

CERNOXES = [
    SHIELD_CERNOX,
    TOP_SCREWED_CERNOX,
    TOP_SAMPLE_CERNOX,
    BOTTOM_SAMPLE_CERNOX,
    BOTTOM_SCREWED_CERNOX,
]
SHIELD_CUTOFF_TEMP: float = 70.0
CERNOX_CUTOFF_TEMP: float = 25.0


def read_file(
    filename: Path,
    channels: list[str],
    experiment_start: datetime | None = None,
    experiment_end: datetime | None = None,
) -> p.DataFrame:
    """
    Reads tab-separated file with measurement data, keeping only the columns with the specified header and the date.
    """
    df = p.DataFrame(
        p.read_csv(filename, sep="\t", index_col=False)[["date"] + channels]
    )
    df["date"] = p.to_datetime(df["date"], format="%Y-%m-%d_%H-%M-%S-%f")
    if experiment_start:
        df = df.loc[df["date"] >= experiment_start]
    if experiment_end:
        df = df.loc[df["date"] <= experiment_end]
    df.set_index("date", inplace=True)
    return df


def cleanup_query(
    min_temp: float = 0, shield_cutoff: float = 70.0, probe_cutoff: float = 25
) -> str:
    return f"""0 < `{SHIELD_CERNOX}` < {shield_cutoff} and \
    0 < `{TOP_SCREWED_CERNOX}` < {probe_cutoff} and \
    0 < `{BOTTOM_SCREWED_CERNOX}` < {probe_cutoff} and \
    0 < `{TOP_SAMPLE_CERNOX}` < {probe_cutoff} and \
    0 < `{BOTTOM_SCREWED_CERNOX}` < {probe_cutoff}"""


fg230 = read_file(
    Path("FG230_monitoring.txt"),
    CERNOXES,
    experiment_start=datetime.fromisoformat("2025-04-29T14:32:00"),
    experiment_end=datetime.fromisoformat("2025-04-29T15:45:00"),
).query(cleanup_query())

fg500 = read_file(
    Path("FG500_monitoring.txt"),
    CERNOXES,
    datetime.fromisoformat("2025-05-30T10:30:00"),
    datetime.fromisoformat("2025-05-30T11:32:00"),
).query(cleanup_query())


fg230.plot().show()
fg500.plot().show()
