#!/usr/bin/python3
# SPDX-License-Identifier: BSD-2-Clause
# Copyright 2022 Arm Ltd.

import signal

def sigint_handler(signum, frame):
    sys.exit(-2)

signal.signal(signal.SIGINT, sigint_handler)

import argparse
import os
import sys
import pprint

import dtschema

strict = False

if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("schema_files", type=str, nargs='*',
                    help="Schema directories and/or files")
    ap.add_argument('-d', '--duplicates', help="Only output properties with more than one type", action="store_true")
    ap.add_argument('-v', '--verbose', help="Additional search path for references", action="store_true")
    ap.add_argument('-V', '--version', help="Print version number",
                    action="version", version=dtschema.__version__)
    args = ap.parse_args()

    if os.path.isfile(args.schema_files[0]):
        schemas = dtschema.load_schema(os.path.abspath(args.schema_files[0]))
    else:
        schemas = dtschema.process_schemas(args.schema_files)
    dtschema.set_schema(schemas)

    props = dtschema.extract_types(schemas)

    if args.duplicates:
        tmp_props = {}
        for k,v in props.items():
            if 'type' in v and len(v['type']) > 1:
                tmp_props[k] = v

        props = tmp_props

    if args.verbose:
        prop_types = props
    else:
        prop_types = {}
        for k,v in props.items():
            if 'type' in v:
                prop_types[k] = v['type']
            else:
                prop_types[k] = None

    try:
        pprint.pprint(prop_types, compact=True)
        # flush output here to force SIGPIPE to be triggered
        # while inside this try block.
        sys.stdout.flush()
    except BrokenPipeError:
        # Python flushes standard streams on exit; redirect remaining output
        # to devnull to avoid another BrokenPipeError at shutdown
        devnull = os.open(os.devnull, os.O_WRONLY)
        os.dup2(devnull, sys.stdout.fileno())
        sys.exit(1)  # Python exits with error code 1 on EPIPE
