#!/usr/bin/env python

from __future__ import print_function
from clarifai.rest import ApiClient, TokenError

"""
the clarifai command line utility

Basically it helps to setup the environmental variables for the API Clients
"""

import os
import sys
import platform
from pprint import pprint
from configparser import ConfigParser
from builtins import input
from subprocess import call


def setup(api_key):
  ''' write back CLARIFAI_API_KEY to config file
      config file is at ~/.clarifai/config
  '''

  os.environ['CLARIFAI_API_KEY'] = api_key

  homedir = os.environ['HOMEPATH'] if platform.system() == 'Windows' else os.environ['HOME']
  CONF_DIR=os.path.join(homedir, '.clarifai')
  if not os.path.exists(CONF_DIR):
    os.mkdir(CONF_DIR)
  elif not os.path.isdir(CONF_DIR):
    raise Exception('%s should be a directory for configurations' % CONF_DIR)

  CONF_FILE=os.path.join(CONF_DIR, 'config')

  parser = ConfigParser()
  parser.optionxform = str

  if os.path.exists(CONF_FILE):
    parser.readfp(open(CONF_FILE, 'r'))

  if not parser.has_section('clarifai'):
    parser.add_section('clarifai')

  # remove CLARIFAI_APP_ID
  if parser.has_option('clarifai', 'CLARIFAI_APP_ID'):
    parser.remove_option('clarifai', 'CLARIFAI_APP_ID')

  # remove CLARIFAI_APP_SECRET
  if parser.has_option('clarifai', 'CLARIFAI_APP_SECRET'):
    parser.remove_option('clarifai', 'CLARIFAI_APP_SECRET')

  parser.set('clarifai', 'CLARIFAI_API_KEY', api_key)

  with open(CONF_FILE, 'w') as fdw:
    parser.write(fdw)

def configure():
  ''' configure clarifai related environmental variables
  '''

  homedir = os.environ['HOMEPATH'] if platform.system() == 'Windows' else os.environ['HOME']
  CONF_FILE=os.path.join(homedir, '.clarifai', 'config')

  if os.environ.get('CLARIFAI_API_KEY'):
    print('Clarifai environmental variables are already set. ')
    api_key = os.environ['CLARIFAI_API_KEY']
    masked_api_key = (len(api_key) - 4) * '*' + api_key[-4:]
  elif os.path.exists(CONF_FILE):
    parser = ConfigParser()
    parser.optionxform = str

    with open(CONF_FILE, 'r') as fdr:
      parser.readfp(fdr) 

    if parser.has_option('clarifai', 'CLARIFAI_API_KEY'):
      api_key = parser.get('clarifai', 'CLARIFAI_API_KEY')
      masked_api_key = (len(api_key) - 4) * '*' + api_key[-4:]
    else:
      masked_api_key = ''
  else:
    masked_api_key = ''

  # setup the APP_ID and APP_SECRET

  api_key_input = input('CLARIFAI_API_KEY: [%s]: ' % masked_api_key)

  if api_key_input:
    setup(api_key_input)
  elif masked_api_key:
    setup(api_key)

  # test the id and secret
  try:
    api = ApiClient()
  except TokenError:
    print('Invalid id/secret to get the token, please verify and try again.')

def diagnose():
  ''' diagnose function
      this will print out essential library and system level info
      to facilitate the troubleshooting when issue occurs
  '''

  print('Clarifai API Diagnosis Info')
  print('-' * 85)

  print('>>>>> OS Version')
  pprint(platform.system())
  print('')

  print('>>>>> Python Version')
  pprint(sys.version)
  print('')

  print('>>>>> Environmental Variables')
  pprint(os.environ)
  print('')

  print('>>>>> Pip Package Info')
  call(['pip', 'freeze'])
  print('')

  print('>>>>> Clarifai Pip Package Info')
  call(['pip', 'show', '-f', 'clarifai'])
  print('')

def print_help():
  ''' print help of this command '''

  print("""
NAME
       clarifai -

DESCRIPTION
       The clarifai Command Line is a tool to manage your api client setup, like
       the environmental variables

SYNOPSIS
          clarifai <command> [parameters]

EXAMPELS
          clarifai config
          clarifai diagnose
          clarifai help
""")

  exit(1)

def main():

  if len(sys.argv) < 2:
    print_help()

  command = sys.argv[1]
  if command == 'configure' or command == 'config':
    configure()
  elif command == 'diagnose':
    diagnose()
  else:
    print_help()


if __name__ == '__main__':
  main()

