#!python
# IBM_PROLOG_BEGIN_TAG
#
# Copyright 2019,2020 IBM International Business Machines Corp.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#           http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
#  implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#
#  IBM_PROLOG_END_TAG
import sys
import importlib
import vapi_cli.cli_utils as cli_utils
from vapi_cli.docopt import docopt

usage_stmt = f"""
Usage:  vision {cli_utils.common_cmd_flags} [-?] <resource> [<args>...]

Where:
{cli_utils.common_cmd_flag_descriptions}
   -?  displays this help message.

   <resource> is required and must be one of:
      categories     -- work with categories within a dataset
      datasets       -- work with datasets
      files          -- work with dataset files (images and/or videos)
      fkeys          -- work with user file metadata keys
      fmetadata      -- work with user file metadata key/value pairs
      object-tags    -- work with object detection tags 
      object-labels  -- work with object detection labels (aka annotations)
      dltasks        -- work with DL training tasks
      trained-models -- work with trained models
      deployed-models -- work with deployed models
      projects       -- work with projects
      users          -- work with users

'vision' provides access to Maximo Visual Inspection resources via the ReST API.
Use 'vision <resource> --help' for more information about operating on a given resource"""

resource_map = {
    "categories": "categories",
    "datasets": "datasets",
    "deployed-models": "deployed-models",
    "dltasks": "dltasks",
    "files": "files",
    "fkeys": "fkeys",
    "fmetadata": "fmetadata",
    "help": "help",
    "obj-labels": "object-labels",
    "obj-tags": "object-tags",
    "object-labels": "object-labels",
    "object-tags": "object-tags",
    "trained-models": "trained-models",
    "projects": "projects",
    "users": "users"
}

if __name__ == "__main__":
    # All of the MVI CLI requires python 3.6 due to format string
    # Make the check in a common location
    if sys.hexversion < 0x03060000:
        sys.exit("Python 3.6 or newer is required to run this program. You have {}.{}."
                 .format(sys.version_info[0], sys.version_info[1]))

    args = docopt(usage_stmt, options_first=True)
    if args is not None:
        #print(f"@@@ args={args}", file=sys.stderr)
        if args["<resource>"] in ["help", None]:
            print(usage_stmt, file=sys.stderr)
        else:
            # argv = [args["<resource>"]] + args["<args>"]
            argv = args["<args>"]
            if argv is None:
                argv = ["--help"]

            # handle abbreviated entities
            resource = args["<resource>"]
            if args["<resource>"] not in resource_map:
                matches = [resource_map[i] for i in resource_map.keys() if i.startswith(resource)]
                if len(matches) == 1:
                    args["<resource>"] = matches[0]
                else:
                    # Generate correct error message and exit (with usage statement)
                    if len(matches) > 1:
                        print(f"ERROR: resource '{resource}' not unique; matches={matches}")
                    else:
                        print(f"ERROR: Unknown resource -- {resource}", file=sys.stderr)
                    print(usage_stmt, file=sys.stderr)
                    exit(1)

            resource = resource_map.get(args["<resource>"], None)

            try:
                pkg = importlib.import_module(f"vapi_cli.{resource}", package=None)
                pkg.main(argv, cmd_flags=args)
            except ModuleNotFoundError as err:
                print(f"ERROR: Unknown resource -- {resource}", file=sys.stderr)
                print(usage_stmt, file=sys.stderr)
                raise err
