#!/usr/bin/env python3
# Copyright 2019 Vitaliy Zakaznikov (TestFlows Test Framework http://testflows.com)
#
# 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.
import sys

import testflows.settings as settings

from testflows._core.exceptions import exception
from testflows._core.cli.text import danger, warning
from testflows._core.cli.arg.exit import *
from testflows._core.cli.arg.parser import parser

try:
    if len(sys.argv) == 1:
        sys.argv.append("-h")

    args, unknown = parser.parse_known_args()
    if unknown:
        raise ExitWithError(f"unknown argument {unknown}")

    if args.debug:
        settings.debug = True

    if args.no_colors:
        settings.no_colors = True

    args.func(args)

except (ExitException, KeyboardInterrupt, Exception) as exc:
    if settings.debug:
        sys.stderr.write(warning(exception(), eol='\n'))
    if not isinstance(exc, KeyboardInterrupt):
        sys.stderr.write(danger("error: " + str(exc).strip()))
    else:
        sys.stderr.write("\n")
    if isinstance(exc, ExitException):
        sys.exit(exc.exitcode)
    else:
        sys.exit(1)
