#!/usr/bin/env python
'''
@file packet_data_base.py

@brief Packet data base class

Copyright (C) Atmosic 2025
'''
import abc
from typing import TypeVar, Type
from lib.bytes_utils import bytes_to_hex

T = TypeVar('T', bound='PacketDataBase')

class PacketDataBase(abc.ABC):
    @abc.abstractmethod
    def to_bytes(self) -> bytes:
        """Serialize packet to bytes.

        Returns:
            bytes: Serialized packet data
        """
        pass

    @classmethod
    @abc.abstractmethod
    def from_bytes(cls: Type[T], data: bytes) -> T:
        """Deserialize packet from bytes.

        Args:
            data: Raw bytes to deserialize

        Returns:
            PacketDataBase: Deserialized packet instance
        """
        pass

    def __len__(self) -> int:
        """Return packet length in bytes.

        Returns:
            int: Length of serialized packet
        """
        return len(self.to_bytes())

    def __str__(self) -> str:
        """String representation for debugging showing hex bytes.

        Returns:
            str: Human-readable representation
        """
        try:
            data = self.to_bytes()
            return f"{self.__class__.__qualname__}({bytes_to_hex(data)})"
        except BaseException as e:
            return f"{self.__class__.__qualname__}(<to_bytes error: {e}>)"

    def __repr__(self) -> str:
        """Detailed string representation for debugging with length and hex.

        Returns:
            str: Detailed representation
        """
        try:
            data = self.to_bytes()
            return f"{self.__class__.__qualname__}(length={len(self)}," \
                f" hex={bytes_to_hex(data)})"
        except BaseException as e:
            return f"{self.__class__.__qualname__}(<to_bytes error: {e}>)"
