""" Extract Analysis ID from a CodeSonar project on disk. """

import argparse
import os
import sys

from cs_client.prj_info import find_prj_files_path, read_aid_txt, AID_TXT


def main(argv):
    """ Commandline program to read analysis ID from a CodeSonar project on disk. """
    linesep = '\n'
    stdout = sys.stdout
    stderr = sys.stderr
    exit_code = 0
    err_msg = None
    argp = argparse.ArgumentParser(
        description='Read Analysis ID from a CodeSonar project on disk.',
        prog='codesonar analysis_id.py')
    argp.add_argument(
        'project_path',
        metavar='project_file',
        help='Path to local CodeSonar project on disk.  Accepts .prj, .prj_files, or file name without extension.')
    argp.add_argument(
        '-strip',
        dest='no_linesep',
        action='store_true',
        help="Don't print a newline after the analysis ID.")
    arg_obj = argp.parse_args(argv[1:])
    project_path = arg_obj.project_path
    should_print_linesep = not arg_obj.no_linesep
    prj_files_path = find_prj_files_path(project_path)
    aid_str = None
    if not prj_files_path:
        err_msg = f'Analysis data files could not be found from path: \'{project_path}\'.'
    else:
        aid_txt_path = os.path.join(prj_files_path, AID_TXT)
        try:
            aid_str = read_aid_txt(aid_txt_path)
        except IOError as ex:
            err_msg = str(ex)
    if aid_str:
        stdout.write(aid_str)
        if should_print_linesep:
            stdout.write(linesep)
        stdout.flush()
    else:
        if err_msg:
            stderr.write(err_msg)
        else:
            stderr.write('Failed to read analysis ID.')
        stderr.write(linesep)
        stderr.flush()
        exit_code = 1
    return exit_code


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