"""The 'compileShellScript' function takes the path to a .env file,
reads the environment variables from the file, and creates a shell script
that checks if the environment variables are already set. If they are not
they are then set using the value from the file. The resulting shell
script is returned as a string including the shebang line such that both
bash and zsh should be able to run the script. """
#  AGPL-3.0 license
#  Copyright (c) 2024 Asger Jon Vistisen
from __future__ import annotations

import time


def _getNotice() -> str:
  """Creates the notice that the shell script is auto-generated by zshpy. """
  autoGeneratedNotice = """This script was auto-generated by the zshpy 
  module. <br> Do not edit this file manually as it is managed 
  automatically meaning that changes will be overwritten at undefined 
  intervals. <br> This particular version of the script was generated on: %s
  """

  text = autoGeneratedNotice % '{{TIME}}'
  paragraphs = [line.strip() for line in text.split('<br>')]
  lines = []
  line = []
  lineLength = 77
  padLeft = '# %02d | '
  padRight = ' | #'
  nLeft = len(padLeft % 69)
  nRight = len(padRight)
  n = lineLength
  n0 = lineLength - nLeft - nRight
  for p in paragraphs:
    for word in p.split():
      if len(word) + len(' '.join(line)) > n0:
        lines.append(line)
        line = []
      line.append(word)
    lines.append(line)
    lines.append(' ')
    line = []
  lines.pop()
  fmtLines = []

  for (i, line) in enumerate(lines):
    left = padLeft % i
    mid = (' '.join(line)).ljust(n0, ' ')
    right = padRight
    fmtLines.append('%s%s%s' % (left, mid, right))
  header = ('_' * (n - 4)).center(n - 2, ' ').center(n, '#')
  footer = ('¨' * (n - 4)).center(n - 2, ' ').center(n, '#')
  out = [header, '\n'.join(fmtLines), footer]
  return '\n'.join(out).replace('{{TIME}}', '\n  ' + time.ctime() + '\n  ')


def compileShellScript(fid: str) -> str:
  """The 'compileShellScript' function takes the path to a .env file,
  reads the environment variables from the file, and creates a shell script
  that checks if the environment variables are already set. If they are not
  they are then set using the value from the file. The resulting shell
  script is returned as a string including the shebang line such that both
  bash and zsh should be able to run the script. """
  from moreworktoy import loadEnv

  envData = loadEnv(fid)

  script = "#!/bin/sh\n"
  #  Include comment explaining that the script is auto-generated by zshpy
  #  and that it should not be edited manually. Also, include a date for
  #  the generation of the script.

  for (key, value) in envData.items():
    script += f"if [ -z ${key} ]; then\n"
    script += f"  export {key}={value}\n"
    script += "fi\n"

  return script


def testLOL() -> str:
  """Testing _getNotice"""
  return _getNotice()
