import json
import os


CONFIG_FILE_PATH = os.path.expanduser('~/.op-dev-config')


def get_config():
  """
  Returns the deserialized CLI config, or an empty dictionary if there was any error
  """
  
  try:
    with open(CONFIG_FILE_PATH) as file:
      serialized_config = file.read()
    return json.loads(serialized_config)
  except FileNotFoundError:
    return {}


def _update_config(config):
  serialized_config = json.dumps(config, indent=2)
  with open(CONFIG_FILE_PATH, 'w') as file:
    file.write(serialized_config)


def run(parser, args):
  secret_group = (args.secret, args.secret_id)
  if any(secret_group) and not all(secret_group):
    parser.error("must specify '--secret-id' and '--secret' together")

  config = get_config()

  update = [ i for i in vars(args) if i != 'cmd' and getattr(args, i) ]
  if update:
    for key in update:
      value = getattr(args, key)
      config[key] = value
    _update_config(config)

  print(json.dumps(config, indent=2))
