# hexdump.py
import sys
from pathlib import Path


def print_hexdump(file_path: Path, max_bytes: int = 1024):
    """
    Reads a binary file and prints its content as a hex dump.
    """
    if not file_path.is_file():
        print(f"Error: File not found at '{file_path}'")
        return

    print(f"--- Hex Dump for {file_path.name} (first {max_bytes} bytes) ---")

    try:
        with open(file_path, "rb") as f:
            offset = 0
            while True:
                # Read 16 bytes at a time
                chunk = f.read(16)
                if not chunk:
                    break

                # Format the offset
                hex_offset = f"{offset:08x}"

                # Format the hex values
                hex_values = " ".join(f"{b:02x}" for b in chunk)

                # Add padding if the line is shorter than 16 bytes
                hex_values = hex_values.ljust(16 * 3 - 1)

                # Format the ASCII representation
                ascii_values = "".join(chr(b) if 32 <= b < 127 else "." for b in chunk)

                print(f"{hex_offset}  {hex_values}  |{ascii_values}|")

                offset += 16
                if offset >= max_bytes:
                    print(f"--- Reached max display limit of {max_bytes} bytes ---")
                    break
    except Exception as e:
        print(f"An error occurred: {e}")


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python hexdump.py <path_to_binary_file>")
        sys.exit(1)

    input_path = Path(sys.argv[1])

    # Aumentiamo il limite per assicurarci di vedere tutta la struttura
    # La CdpStsPayload è di qualche centinaio di byte, 1024 è più che sufficiente.
    print_hexdump(input_path, max_bytes=1024)
