"""
@file hci_packet.py
@brief Base HCI packet classes

Copyright (C) Atmosic 2025
"""
from __future__ import annotations
from typing import Type, TypeVar

from packet.base.packet_data_base import PacketDataBase


class HciPacketBase(PacketDataBase):
    """Base class for all HCI packets with payload management"""

    def __init__(self):
        self.payload: bytearray = bytearray(b"")
        self.valid_payload_size: int = 0

    def adjust_payload_size(self, new_size: int) -> None:
        """Adjust valid_payload_size and extend payload if needed"""
        if len(self.payload) < new_size:
            # Extend payload with zeros if it's too small
            self.payload.extend(b'\x00' * (new_size - len(self.payload)))
        # Always update valid_payload_size
        self.valid_payload_size = new_size

    def to_bytes(self) -> bytes:
        self.update_before_to_bytes()
        # Return only the valid portion of payload
        return bytes(self.payload[:self.valid_payload_size])

    def update_before_to_bytes(self) -> None:
        """Override in subclasses to update fields before conversion"""
        pass

    @classmethod
    def from_bytes(cls: Type['THciPacket'], data: bytes) -> 'THciPacket':
        packet = cls()
        packet.payload = bytearray(data)
        return packet


THciPacket = TypeVar('THciPacket', bound=HciPacketBase)
