"""Tests for energy consumption model and API module."""

from __future__ import annotations

import pytest

from pybyd._api.energy import _build_energy_inner, _parse_energy_consumption
from pybyd.config import BydConfig
from pybyd.models.energy import EnergyConsumption


class TestBuildEnergyInner:
    def test_payload_structure(self, test_config: BydConfig) -> None:
        inner = _build_energy_inner(test_config, "VIN123", 1700000000000)
        assert inner["vin"] == "VIN123"
        assert inner["timeStamp"] == "1700000000000"
        assert inner["deviceType"] == test_config.device.device_type
        assert inner["imeiMD5"] == test_config.device.imei_md5
        assert inner["networkType"] == test_config.device.network_type
        assert inner["version"] == test_config.app_inner_version
        assert len(inner["random"]) == 32  # 16 hex bytes = 32 chars

    def test_random_is_unique(self, test_config: BydConfig) -> None:
        a = _build_energy_inner(test_config, "VIN", 0)
        b = _build_energy_inner(test_config, "VIN", 0)
        assert a["random"] != b["random"]


class TestParseEnergyConsumption:
    def test_full_data(self) -> None:
        data = {
            "vin": "VIN123",
            "totalEnergy": "150.5",
            "avgEnergyConsumption": "15.2",
            "electricityConsumption": "120.3",
            "fuelConsumption": "30.2",
        }
        result = _parse_energy_consumption(data)
        assert result.vin == "VIN123"
        assert result.total_energy == 150.5
        assert result.avg_energy_consumption == 15.2
        assert result.electricity_consumption == 120.3
        assert result.fuel_consumption == 30.2
        assert result.raw is data

    def test_missing_fields(self) -> None:
        data = {"vin": "VIN456"}
        result = _parse_energy_consumption(data)
        assert result.vin == "VIN456"
        assert result.total_energy is None
        assert result.avg_energy_consumption is None
        assert result.electricity_consumption is None
        assert result.fuel_consumption is None

    def test_empty_data(self) -> None:
        result = _parse_energy_consumption({})
        assert result.vin == ""
        assert result.total_energy is None


class TestEnergyConsumptionModel:
    def test_frozen(self) -> None:
        ec = EnergyConsumption(
            vin="V",
            total_energy=1.0,
            avg_energy_consumption=None,
            electricity_consumption=None,
            fuel_consumption=None,
            raw={},
        )
        with pytest.raises(AttributeError):
            ec.vin = "other"  # type: ignore[misc]
