"""
candump_loader.py

Parses .log files generated by `candump`.

Expected format per line:
(timestamp) interface ID#data

Example:
(1684540301.123456) vcan0 123#DEADBEEF

Returns a normalized pandas DataFrame.
"""

import re

import pandas as pd


def load_candump_log(file_path: str) -> pd.DataFrame:
    pattern = re.compile(r"\(([\d\.]+)\)\s+\S+\s+([0-9A-Fa-f]+)#([\dA-Fa-f]*)")
    records = []

    with open(file_path, "r") as f:
        for line in f:
            match = pattern.match(line.strip())
            if match:
                timestamp = float(match.group(1))
                can_id = match.group(2)
                data_hex = match.group(3)
                data = " ".join(data_hex[i : i + 2] for i in range(0, len(data_hex), 2))
                dlc = len(data_hex) // 2
                records.append(
                    {"timestamp": timestamp, "id": can_id, "dlc": dlc, "data": data}
                )

    return pd.DataFrame(records)
