import argparse
import sys
from steggynography import __project_name__, __version__
from steggynography.encode import encode
from steggynography.decode import decode
from steggynography.errors import ImgFrmtErr, EncFitErr, HeadrErr, HeadrVersnErr

def main():
  # steggynography
  parser = argparse.ArgumentParser()
  parser.prog = "steggynography"
  parser.description = "A simple steganography engine that uses " \
                       "LSB to hide ASCII text within images."
  subparsers = parser.add_subparsers(dest="cmd")

  # encode
  enc_desc = "Encodes a message within an image file and " \
             "writes it to a separate image file."
  enc_parser = subparsers.add_parser("encode", description=enc_desc, help=enc_desc)
  
  enc_parser.add_argument("img_in", help="Path to the input image file (read).")
  enc_parser.add_argument("msg", help="ASCII plaintext to be encoded into the image file.")
  enc_parser.add_argument("img_out", help="Path to the output image file (write).")

  # decode
  dec_desc = "Decodes a secret message within " \
             "an image file and writes it to a text file."
  dec_parser = subparsers.add_parser("decode", description=dec_desc, help=dec_desc)
  
  dec_parser.add_argument("img_in", help="Path to the input image file (read).")
  dec_parser.add_argument("txt_out", help="Path to the output text file (write).")

  # argument checking
  args = parser.parse_args()
  if args.cmd == "encode":
    try:
      encode(args.img_in, args.msg, args.img_out)
    except ImgFrmtErr as e:
      print(f"Invalid image format used: '{e.img_path}'.")
      sys.exit(1)
    except EncFitErr as e:
      print(f"Message is too long ({e.enc_size} bits) for image ({e.img_size} bytes).")
      sys.exit(1)
  elif args.cmd == "decode":
    try:
      decode(args.img_in, args.txt_out)
    except ImgFrmtErr as e:
      print(f"Invalid image format used: '{e.img_path}'.")
      sys.exit(1)
    except HeadrVersnErr as e:
      print(f"Cannot decode image as it was encoded with a different version of this program.")
      print(f"- image version = {e.version}")
      print(f"- {__project_name__} version = {__version__}")
      sys.exit(1)
    except HeadrErr as e:
      print(f"Cannot decode image as it was not encoded with the '{__project_name__}' program.")
      sys.exit(1)

