"""Abbott FreeStyle Libre / LibreView CSV adapter.

Real LibreView CSV pattern (simplified):
  Device,Serial Number,Device Timestamp,Record Type,Historic Glucose mg/dL,Scan Glucose mg/dL,...
"""

import os
import pandas as pd

NAME = "Libre LibreView"
SENSOR_TYPE = "libre3"

SIGNATURE_HINTS = (
    ("libre", None),
    (None, "Historic Glucose mg/dL"),
)


def matches(path: str) -> bool:
    fname = os.path.basename(path).lower()
    if "libre" in fname:
        return True
    if not path.lower().endswith(".csv"):
        return False
    try:
        with open(path, "r", encoding="utf-8", errors="ignore") as f:
            head = f.read(2048)
        return ("Historic Glucose mg/dL" in head) or ("Device Timestamp" in head and "Glucose" in head)
    except Exception:
        return False


def parse(path: str) -> pd.DataFrame:
    df = pd.read_csv(path)
    ts_col = None
    hist_col = None
    scan_col = None
    pid_col = None
    serial_col = None
    for c in df.columns:
        cl = c.lower()
        if ts_col is None and ("timestamp" in cl or "time" in cl):
            ts_col = c
        if hist_col is None and "historic glucose" in cl:
            hist_col = c
        if scan_col is None and "scan glucose" in cl:
            scan_col = c
        if pid_col is None and ("patient" in cl or "subject" in cl):
            pid_col = c
        if serial_col is None and "serial" in cl:
            serial_col = c
    # Prefer Patient/Subject; fall back to Serial only if no patient col
    if pid_col is None:
        pid_col = serial_col

    if ts_col is None or (hist_col is None and scan_col is None):
        return pd.DataFrame()

    glu = None
    if hist_col is not None and scan_col is not None:
        glu = pd.to_numeric(df[hist_col], errors="coerce").fillna(
            pd.to_numeric(df[scan_col], errors="coerce")
        )
    elif hist_col is not None:
        glu = pd.to_numeric(df[hist_col], errors="coerce")
    else:
        glu = pd.to_numeric(df[scan_col], errors="coerce")

    out = pd.DataFrame()
    out["subject_id"] = df[pid_col].astype(str) if pid_col else "LIB_SUBJ_01"
    out["timestamp_KST"] = pd.to_datetime(df[ts_col], errors="coerce")
    out["glucose_mg_dl"] = glu
    out["sensor_type"] = SENSOR_TYPE
    out["pump_basal_uph"] = pd.NA
    out["pump_bolus_u"] = pd.NA
    out["meal_carb_g"] = pd.NA
    out["exercise_flag"] = 0
    out = out.dropna(subset=["timestamp_KST", "glucose_mg_dl"]).reset_index(drop=True)
    return out
