"""
Simple wrapper for main SfePy commands (scripts).

Available commands are dynamically defined by presence of *.py scripts
in default directory (scripts-common).
"""
import os.path as op
import sys
import argparse
import subprocess

import sfepy

def get_commands():
    """
    Get available commands (and corresponding scripts) for SfePy wrapper.

    Returns
    -------
    commands : dict
        The command : path_to_script dictionary.
    """
    scripts = [
        'phonon.py',
        'extractor.py',
        'homogen.py',
        'postproc.py',
        'probe.py',
        'run_tests.py',
        'simple.py',
    ]

    if not sfepy.in_source_tree:
        bin_dir = op.normpath(op.join(sfepy.data_dir, 'script'))
        scripts = [op.normpath(op.join(bin_dir, i)) for i in scripts]

    cmd = [op.splitext(op.basename(i))[0] for i in scripts]
    commands = dict(zip(cmd, scripts))

    return commands

def main():
    cmd_list = get_commands()

    parser = argparse.ArgumentParser(
        description='Simple wrapper for main SfePy commands.',
        usage='%(prog)s [command] [options]'
    )

    parser.add_argument(
        '-v',
        '--version',
        action='version',
        version='%(prog)s ' + sfepy.__version__
    )

    parser.add_argument(
        '-w',
        '--window',
        help='use alternative (pythonw) interpreter',
        action='store_true',
        dest='py_cmd'
    )

    parser.add_argument(
        'command',
        choices=sorted(cmd_list.keys()),
        help='Available SfePy command(s).')

    parser.add_argument(
        'options',
        nargs=argparse.REMAINDER,
        help='Additional options passed directly to selected [command].')

    if not len(sys.argv) > 1:
        parser.print_help()
        return

    options = parser.parse_args()
    py_cmd = sys.executable if not options.py_cmd else 'pythonw'
    if not py_cmd: py_cmd = 'python'

    args = [py_cmd, cmd_list[options.command]] + options.options

    subprocess.call(args)

if __name__ == '__main__':
    main()
