from steggynography import __version__, dec_to_bin, bin_to_dec, bin_to_ascii
from steggynography.errors import HeadrErr, HeadrVersnErr
from itertools import accumulate

magic = "stgaustn"
# number of bytes for each component of header
headr_spec = (8, 1, 1, 1, 4) # magic, version (maj, min, patch), length
# length in bits
headr_len = sum(headr_spec) * 8
assert(headr_spec[0] == len(magic))

def make_headr_bin(payld_len : int) -> list[int]:
  headr_bin : list[int] = []
  
  # magic
  for i in range(headr_spec[0]):
    c = magic[i]
    headr_bin += dec_to_bin(ord(c), 8)

  # version
  for i in range(3):
    headr_bin += dec_to_bin(__version__[i], headr_spec[1 + i] * 8)

  # length
  headr_bin += dec_to_bin(payld_len, headr_spec[4] * 8)
  
  return headr_bin

def parse_headr_bin(headr_bin : list[int]) -> tuple[str, int, int, int, int]:
  # index into header of each component
  spec_inds = [e * 8 for e in headr_spec]
  spec_inds = list(accumulate(spec_inds))

  # magic
  _magic = bin_to_ascii(headr_bin[:spec_inds[0]])
  if _magic != magic:
    raise HeadrErr()

  # version
  version = [bin_to_dec(headr_bin[spec_inds[i]:spec_inds[i+1]]) for i in range(3)]
  if (version != __version__):
    raise HeadrVersnErr(version)

  # length
  length = bin_to_dec(headr_bin[spec_inds[3]:spec_inds[4]])

  return (_magic, version[0], version[1], version[2], length)

