#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
    Blockstack-client
    ~~~~~
    copyright: (c) 2014-2015 by Halfmoon Labs, Inc.
    copyright: (c) 2016-2017 by Blockstack.org

    This file is part of Blockstack-client.

    Blockstack-client is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Blockstack-client is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    You should have received a copy of the GNU General Public License
    along with Blockstack-client.  If not, see <http://www.gnu.org/licenses/>.
"""

import os
import sys

if sys.version_info.major != 2:
    raise Exception("Python 3 is not supported")

if sys.version_info.minor < 7:
    raise Exception("Python 2.7 or greater is required")

import traceback
import json

# Hack around absolute paths
current_dir = os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(current_dir + "/../")

sys.path.insert(0, parent_dir)

from blockstack_client.cli import run_cli, exit_with_error
from blockstack_client.config import get_logger, configure, CONFIG_PATH, VERSION
from blockstack_client.utils import pretty_print


if __name__ == '__main__':

    log = get_logger()
       
    try:
        result = run_cli()
        if isinstance(result, dict) and 'error' in result:
            print >> sys.stderr, result['error']
            sys.exit(1)
        elif isinstance(result, dict):
            if 'raw' in result.get('pragmas', []):
                print result.get('result', result)

            else:
                print json.dumps(result.get('result', result), indent=4, sort_keys=True)

            sys.exit(0)

    except Exception as e:
        log.exception(e)
        error_message = "Unexpected error:\n%s" % traceback.format_exc()
        help_message = 'Try getting latest version of CLI'
        help_message += ' with "sudo pip install blockstack --upgrade"'
        exit_with_error(error_message, help_message)
