"""Shared fixtures and helpers for pyfitparsernative tests."""

import os
from collections import Counter

DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
SAMPLE_FIT = os.path.join(DATA_DIR, "garmin_bike_ride.fit")

# Numeric session fields to compare between parsers.
# Timestamps and enum fields are excluded: garmin-fit-sdk returns tz-aware
# datetimes and string enum values, while pyfitparsernative returns ISO strings
# and raw integers respectively.
SESSION_NUMERIC_FIELDS = [
    "avg_power",
    "max_power",
    "normalized_power",
    "avg_heart_rate",
    "max_heart_rate",
    "avg_cadence",
    "max_cadence",
    "total_calories",
    "total_ascent",
    "total_descent",
    "total_work",
    "avg_temperature",
    "max_temperature",
]


def garmin_sdk_parse(path: str) -> list[dict]:
    """Parse with garmin-fit-sdk and return a flat list of message dicts.

    Each dict includes a ``"message_type"`` key (e.g. ``"session"``,
    ``"record"``) derived from the garmin-fit-sdk grouping key with the
    ``_mesgs`` suffix stripped.  Messages are ordered per-type but
    inter-type ordering is not guaranteed to match the original file.
    """
    from garmin_fit_sdk import Decoder, Stream

    stream = Stream.from_file(path)
    decoder = Decoder(stream)
    messages, _ = decoder.read()

    result = []
    for key, records in messages.items():
        if not isinstance(key, str):
            continue
        msg_type = key.removesuffix("_mesgs")
        for record in records:
            d = dict(record)
            d["message_type"] = msg_type
            result.append(d)
    return result


def messages_by_type(messages: list[dict]) -> dict[str, list[dict]]:
    """Group a flat message list by ``message_type``."""
    grouped: dict[str, list[dict]] = {}
    for msg in messages:
        grouped.setdefault(msg["message_type"], []).append(msg)
    return grouped


def message_type_counts(messages: list[dict]) -> Counter:
    """Return a Counter of message types."""
    return Counter(msg["message_type"] for msg in messages)
