from gnuradio import gr
import numpy as np

class file_overwrite_sink_bytes(gr.sync_block):
    """
    A GNU Radio sink block that writes incoming bytes to a file,
    overwriting the file on each call to work().
    """

    def __init__(self, filename=""):
        gr.sync_block.__init__(
            self,
            name="file_overwrite_sink_bytes",
            in_sig=[np.byte],
            out_sig=None
        )
        self.filename = filename

    def work(self, input_items, output_items):
        data = input_items[0]

        # Convert the incoming bytes to a string
        try:
            text = bytes(data).decode('utf-8', errors='replace')
        except Exception as e:
            text = f"[decode error: {e}]"

        # Open in text mode and overwrite each call
        with open(self.filename, 'w', encoding='utf-8') as f:
            f.write(text)

        f.close()
        return len(data)
