import sys, os, glob
import optparse


def show_help(option, opt, value, parser):
    parser.print_help()
    sys.exit(-1)


def show_version(option, opt, value, parser):
    print("OpenStructure " + ost.__version__)
    sys.exit(0)


def interactive_flag(option, opt, value, parser):
    pass


def stop():
    sys.exit(0)


def get_options_parser(usage):
    parser = OstOptionParser(usage=usage, conflict_handler="resolve", prog="ost")
    parser.add_option(
        "-i",
        "--interactive",
        action="callback",
        callback=interactive_flag,
        help="start interpreter interactively (must be first parameter, ignored otherwise)",
    )
    parser.add_option(
        "-h",
        "--help",
        action="callback",
        callback=show_help,
        help="show this help message and exit",
    )
    parser.add_option(
        "-V",
        "--version",
        action="callback",
        callback=show_version,
        help="show OST version and exit",
    )
    parser.add_option(
        "-v",
        "--verbosity_level",
        action="store",
        type="int",
        dest="vlevel",
        default=2,
        help="sets the verbosity level [default: %default]",
    )
    parser.disable_interspersed_args()
    return parser


usage = """
    ost [ost options] [script to execute] [script parameters]
    ost [action name] [action options]
    
The following actions are available:
"""

action_path = os.path.abspath(os.environ.get("OST_EXEC_DIR", ""))
for action in sorted(glob.glob(os.path.join(action_path, "ost-*"))):
    usage += "  %s\n" % action[len(action_path) + 5 :]

usage += '\nEach action should respond to "--help".'


class OstOptionParser(optparse.OptionParser):
    def __init__(self, **kwargs):
        optparse.OptionParser.__init__(self, **kwargs)

    def exit(self, status_code, error_message):
        print(error_message, end=" ")
        sys.exit(-1)


_site_packs = "python%d.%d/site-packages" % sys.version_info[0:2]
_base_dir = os.getenv("DNG_ROOT")
sys.path.insert(0, os.path.join(_base_dir, "lib", _site_packs))

from ost import *
import ost

parser = get_options_parser(usage)
(options, args) = parser.parse_args()

HistoryFile = os.path.expanduser("~/.ost_history")

# we are not in GUI mode.
gui_mode = False

sys.ps1 = "ost> "
sys.ps2 = "..... "
sys.argv = sys.argv[1:]
home = os.getenv("HOME") or os.getenv("USERPROFILE")
_ostrc = os.path.join(home, ".ostrc")
if os.path.exists(_ostrc):
    try:
        exec(compile(open(_ostrc).read(), _ostrc, "exec"))
    except Exception as e:
        print(e)

PushVerbosityLevel(options.vlevel)

# this should probably only be added when running an interactive shell
sys.path.append(".")

if len(parser.rargs) > 0:
    script = parser.rargs[0]
    sys_argv_backup = sys.argv
    sys.argv = parser.rargs
    try:
        exec(compile(open(script, "rb").read(), script, "exec"))
    finally:
        sys.argv = sys_argv_backup
