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

import pathlib
import pickle

import wk


# STATIC VARIABLES
OPTIONS = {
  'Cloning / Imaging': 'ddrescue-TUI',
  'Hardware Diagnostics': 'Hardware-Diagnostics',
  }


def get_debug_prefix() -> str:
  """Ask what we're debugging, returns log dir prefix."""
  menu = wk.ui.cli.Menu(title=f'{wk.cfg.main.KIT_NAME_FULL}: Debugging Menu\n')
  for name, prefix in OPTIONS.items():
    menu.add_option(name, {'Prefix': prefix})
  selection = menu.simple_select()
  return selection[1]['Prefix']

def get_debug_path() -> pathlib.Path:
  """Get debug path."""
  log_dir = pathlib.Path('~/Logs').expanduser().resolve()
  debug_paths = []
  prefix = get_debug_prefix()

  # Build list of options
  for item in log_dir.iterdir():
    if item.is_dir() and item.name.startswith(prefix):
      debug_paths.append(item.joinpath('debug'))
  debug_paths = [item for item in debug_paths if item.exists()]
  debug_paths.sort()

  # Safety check
  if not debug_paths:
    wk.ui.cli.abort('No logs found, aborting.')

  # Use latest option
  if wk.ui.cli.ask('Use latest session?'):
    return debug_paths[-1]

  # Select from list
  menu = wk.ui.cli.Menu(title=f'{wk.cfg.main.KIT_NAME_FULL}: Debugging Menu\n')
  for item in debug_paths:
    menu.add_option(item.parent.name, {'Path': item})
  selection = menu.simple_select()

  # Done
  return selection[1]['Path']


if __name__ == '__main__':
  # Leaving this at the global level
  try:
    debug_path = get_debug_path()
  except SystemExit:
    pass
  else:
    state = None

    # Load pickle
    with open(debug_path.joinpath('state.pickle'), 'rb') as f:
      state = pickle.load(f)
