"""Data models for Hue lamp control and alarm operations."""

from __future__ import annotations

import struct
from dataclasses import dataclass
from datetime import datetime


@dataclass(frozen=True)
class Config:
    device_name: str
    timeout: float


@dataclass
class AlarmProperties:
    active: bool
    timestamp: datetime
    mystery_bytes: bytes
    name: str


@dataclass
class Alarm:
    _id: int
    raw: bytes
    payload: bytes
    payload_length: int
    properties: AlarmProperties

    def is_wake_up_or_sleep(self) -> bool:
        """Wakeup/sleep alarms contain a fixed FFFF_FFFF marker."""
        return b"\xff\xff\xff\xff" in self.payload

    def extract_timer_duration_seconds(self) -> int:
        """Read timer duration from the two bytes before the nearest 00 00 pre-name marker."""
        from huec.lib.parsers import find_alarm_name_segment

        name_length_index, _ = find_alarm_name_segment(self.raw)
        marker_index = name_length_index - 2
        if marker_index < 2:
            raise ValueError(
                f"Timer marker out of bounds for slot 0x{self._id:04x}: {self.raw.hex()}"
            )
        if self.raw[marker_index] != 0x00 or self.raw[marker_index + 1] != 0x00:
            raise ValueError(f"Timer duration marker not found before name: {self.raw.hex()}")
        return struct.unpack_from("<H", self.raw, marker_index - 2)[0]


@dataclass(frozen=True)
class AlarmListResult:
    raw: bytes
    slot_ids: list[int]


@dataclass(frozen=True)
class AlarmEnableResult:
    slot_id: int
    ack: bytes
    ack_ok: bool
    confirm: bytes
    confirm_ok: bool

    def is_ok(self):
        return self.ack_ok and self.confirm_ok


@dataclass(frozen=True)
class AlarmDeleteResult:
    slot_id: int
    command: bytes
    ack: bytes
    confirm: bytes
    ack_ok: bool
    confirm_ok: bool

    def is_ok(self):
        return self.ack_ok and self.confirm_ok
