#!/usr/bin/env python3
# vim: sts=2 sw=2 ts=2
"""WizardKit: Upload Logs"""

import datetime
import os
import pathlib

import pytz
import requests

import wk


# STATIC VARIABLES
LOG_DIR = pathlib.Path('~/Logs').expanduser().resolve()
PLATFORM = wk.std.PLATFORM.replace('Darwin', 'macOS')
TIMEZONE = pytz.timezone(wk.cfg.main.LINUX_TIME_ZONE)
NOW = datetime.datetime.now(tz=TIMEZONE)


# Safety check
if PLATFORM not in ('macOS', 'Linux'):
  raise OSError(f'This script is not supported under {PLATFORM}')


# Functions
def compress(reason):
  dest = pathlib.Path(f'~/{reason}_{NOW.strftime("%Y-%m-%dT%H%M%S%z")}.txz')
  dest = dest.expanduser().resolve()
  cmd = ['tar', 'caf', dest.name, LOG_DIR.name]
  wk.exe.run_program(cmd, check=False)
  return dest


def compress_live_macos(reason):
  """Compress log_dir using the RAM disk."""
  dest = pathlib.Path(
    f'/Volumes/RAM_Disk/{reason}_{NOW.strftime("%Y-%m-%dT%H%M%S%z")}.txz',
    )
  tmp_file = dest.with_suffix('.tar')
  cmd = ['tar', '-cf', tmp_file.name, LOG_DIR.name]
  wk.exe.run_program(cmd, check=False)
  cmd = ['xz', '-z', tmp_file.name]
  wk.exe.run_program(cmd, check=False)
  tmp_file = tmp_file.with_suffix('.tar.xz')
  tmp_file.rename(dest.name)
  return dest


def compress_and_upload(reason='Testing'):
  """Upload compressed log_dir to the crash server."""
  server = wk.cfg.net.CRASH_SERVER
  upload_args = {
    'headers': server['Headers'],
    'auth': (server['User'], server['Pass']),
    }

  # Compress LOG_DIR (relative to parent dir)
  if os.path.exists('/.wk-live-macos'):
    dest = compress_live_macos(reason)
  else:
    dest = compress(reason)
  upload_args['data'] = dest.read_bytes()

  # Upload compressed data
  url = f'{server["Url"]}/{dest.name}'
  result = requests.put(url, **upload_args)

  # Check result
  if not result.ok:
    raise wk.std.GenericError('Failed to upload logs')


def main() -> None:
  """Upload logs for review."""
  lines = []
  try_and_print = wk.ui.cli.TryAndPrint()

  # Set log
  wk.log.update_log_path(dest_name='Upload-Logs', timestamp=True)

  # Instructions
  wk.ui.cli.print_success(f'{wk.cfg.main.KIT_NAME_FULL}: Upload Logs')
  wk.ui.cli.print_standard('')
  wk.ui.cli.print_standard('Please state the reason for the review.')
  wk.ui.cli.print_info('  End note with an empty line.')
  wk.ui.cli.print_standard('')

  # Get reason note
  while True:
    text = wk.ui.cli.input_text('> ')
    if not text:
      lines.append('')
      break
    lines.append(text)
  with open(f'{LOG_DIR}/__reason__.txt', 'a') as _f:
    _f.write('\n'.join(lines))

  # Compress and upload logs
  os.chdir(LOG_DIR.parent)
  print(os.getcwd())
  result = try_and_print.run(
    message='Uploading logs...',
    function=compress_and_upload,
    reason='Review',
    )
  if not result['Failed']:
    raise SystemExit(1)


def upload_log_dir(reason='Testing') -> None:
  """Upload compressed log_dir to the crash server."""
  server = wk.cfg.net.CRASH_SERVER
  dest = pathlib.Path(f'~/{reason}_{NOW.strftime("%Y-%m-%dT%H%M%S%z")}.txz')
  dest = dest.expanduser().resolve()

  # Compress LOG_DIR (relative to parent dir)
  os.chdir(LOG_DIR.parent)
  cmd = ['tar', 'caf', dest.name, LOG_DIR.name]
  wk.exe.run_program(cmd, check=False)

  # Upload compressed data
  url = f'{server["Url"]}/{dest.name}'
  result = requests.put(
    url,
    data=dest.read_bytes(),
    headers=server['Headers'],
    auth=(server['User'], server['Pass']),
    )

  # Check result
  if not result.ok:
    raise wk.std.GenericError('Failed to upload logs')


if __name__ == '__main__':
  main()
