"""Tests for MXAccess value conversion helpers."""

import json
import re
from datetime import datetime, timezone
from pathlib import Path

from google.protobuf.json_format import ParseDict

from zb_mom_ww_mxgateway.generated import mxaccess_gateway_pb2 as pb
from zb_mom_ww_mxgateway.values import from_mx_value, to_mx_value

FIXTURE_ROOT = Path(__file__).resolve().parents[2] / "proto" / "fixtures" / "behavior"


def test_value_conversion_fixtures_project_expected_oneof_kind() -> None:
    payload = json.loads(
        (FIXTURE_ROOT / "values" / "value-conversion-cases.json").read_text(
            encoding="utf-8",
        ),
    )

    for case in payload["cases"]:
        value = ParseDict(case["value"], pb.MxValue())
        projection = from_mx_value(value)

        assert projection.kind == _snake_case(case["expectedKind"])
        assert projection.raw is value


def test_to_mx_value_supports_scalar_and_array_inputs() -> None:
    assert to_mx_value(True).WhichOneof("kind") == "bool_value"
    assert to_mx_value(12).int32_value == 12
    assert to_mx_value(2**40).int64_value == 2**40
    assert to_mx_value(12.5).double_value == 12.5
    assert to_mx_value("abc").string_value == "abc"
    assert to_mx_value([1, 2]).array_value.int32_values.values == [1, 2]
    assert to_mx_value(["a", "b"]).array_value.string_values.values == ["a", "b"]


def test_to_mx_value_uses_utc_timestamps() -> None:
    value = to_mx_value(datetime(2026, 1, 1, 0, 0, 4, tzinfo=timezone.utc))

    assert value.data_type == pb.MX_DATA_TYPE_TIME
    assert value.timestamp_value.seconds == 1767225604


def _snake_case(value: str) -> str:
    return re.sub(r"(?<!^)(?=[A-Z])", "_", value).lower()
