""" Import SARIF static analysis results to observing CodeSonar process. """

import argparse
import os
import sys

from gtr import gthome

import add_source_files


def main(argv):
    all_source_languages = add_source_files.get_source_languages()
    # We want to support the arguments that sarif_import.py supports plus a few more:
    parser = argparse.ArgumentParser(
        prog=os.path.basename(argv[0]),
        description="Import Sarif files into a CodeSonar analysis")
    parser.add_argument(
        'inputs',
        metavar='SARIF',
        nargs='*',
        help='SARIF file to import')
    # --prjfiles and --uid are used by sarif_import internally,
    #  support the flags here for the sake of completeness:
    parser.add_argument('--prjfiles', help=argparse.SUPPRESS)
    parser.add_argument('--uid', help=argparse.SUPPRESS)
    parser.add_argument(
        '-include-sources',
        metavar='PATTERN',
        dest='source_patterns',
        action='append',
        type=(lambda s: ('-include', s)),
        help="File pattern for source files to include when importing.")
    parser.add_argument(
        '-exclude-sources',
        metavar='PATTERN',
        dest='source_patterns',
        action='append',
        type=(lambda s: ('-exclude', s)),
        help="File pattern for source files to exclude when importing.")
    parser.add_argument(
        '-source-max-bytes',
        dest='source_max_size',
        type=int,
        default=500_000,
        help="The maximum size in bytes for any included source file.")
    parser.add_argument(
        '-source-language',
        dest='source_language',
        default='',
        choices=(('',) + tuple(all_source_languages)),
        help="Language to associate with all source file arguments, by default language is inferred from file extension.")
    # Allow --prefix for consistency with sarif_import
    parser.add_argument(
        '-require-source', '--require-source',
        action='store_true',
        default=False,
        help='Only import warnings with source.')
    parser.add_argument(
        '-analyzer', '--analyzer',
        dest='analyzer',
        help='Tune the import operation to the style of SARIF typically produced by a particular tool.')
    parser.add_argument(
        '-path-base',
        dest='default_path_base',
        help='Base directory for relative source file paths in all SARIF results.  Defaults to directory containing the SARIF file.')
    parser.add_argument(
        '-path-baseid', '--path-baseid',
        nargs=2,
        dest='path_bases',
        action='append',
        help='ID and File path to substitute for SARIF originalUriBaseId.  Path will be converted to a URI.')
    parser.add_argument(
        '-staticcheck-list', '--staticcheck-list',
        dest='go_staticcheck_rule_file',
        help='Path to output of `staticcheck -list-checks` to use for populating warning class names.')
    parser.add_argument(
        '-staticcheck', '--staticcheck',
        dest='go_staticcheck',
        help='Path to `staticcheck` executable to query for warning class names.'
            +' --staticcheck-list option takes precedence over --staticcheck.')
    args = parser.parse_args(argv[1:])

    # If any source file patterns were provided,
    #  call add_source_files.py to add them to the analysis:
    if args.source_patterns:
        srcs_argv = [argv[0]]
        if args.source_max_size:
            srcs_argv.extend(['-max-bytes', str(args.source_max_size)])
        if args.source_language:
            srcs_argv.extend(['-language', args.source_language])
        for flag, pattern in args.source_patterns:
            srcs_argv.append(flag)
            srcs_argv.append(pattern)
        returncode = add_source_files.main(srcs_argv)
        if returncode:
            return returncode

    # Assemble a commandline containing non-source related arguments
    #  for sarif_import
    import_argv = [argv[0]]
    if args.prjfiles:
        import_argv.extend(['--prjfiles', args.prjfiles])
    if args.uid:
        import_argv.extend(['--uid', args.uid])
    if args.require_source:
        import_argv.extend(['--require-source'])
    if args.analyzer:
        import_argv.extend(['--analyzer', args.analyzer])
    if args.default_path_base:
        import_argv.extend(['--path-base', args.default_path_base])
    if args.path_bases:
        for baseid, path in args.path_bases:
            import_argv.extend(['--path-baseid', baseid, path])
    if args.go_staticcheck_rule_file:
        import_argv.extend(['--staticcheck-list', args.go_staticcheck_rule_file])
    if args.go_staticcheck:
        import_argv.extend(['--staticcheck', args.go_staticcheck])
    import_argv.extend(args.inputs)

    sys.path.append(os.path.join(gthome(), 'codesonar', 'py', 'sarif'))
    import sarif_import
    return sarif_import.main(import_argv)


if __name__ == "__main__":
    sys.exit(main(sys.argv))
