"""
"""

import argparse
import logging
import sys
import requests

from sec_filings_api import __version__

__author__ = "paul.t.jensen"
__copyright__ = "paul.t.jensen"
__license__ = "MIT"

_logger = logging.getLogger(__name__)


# ---- Python API ----
# The functions defined in this section can be imported by users in their
# Python scripts/interactive interpreter, e.g. via
# `from sec_filings_api.skeleton import fib`,
# when using this Python module as a library.


def get():
    try:
        headers = {
            'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
        }
        session = requests.Session()
        response = session.get('https://data.sec.gov/submissions/CIK0001649339.json', timeout=5, headers=headers)
        response.raise_for_status()
        return response
    except requests.exceptions.HTTPError as errHttp:
        print(errHttp)
    except requests.exceptions.ConnectionError as errConn:
        print(errConn)
    except requests.exceptions.Timeout as errTimeout:
        print(errTimeout)
    except requests.exceptions.RequestException as errRequest:
        print(errRequest)


# ---- CLI ----
# The functions defined in this section are wrappers around the main Python
# API allowing them to be called directly from the terminal as a CLI
# executable/script.


def parse_args(args):
    """Parse command line parameters

    Args:
      args (List[str]): command line parameters as list of strings
          (for example  ``["--help"]``).

    Returns:
      :obj:`argparse.Namespace`: command line parameters namespace
    """
    parser = argparse.ArgumentParser(description="Just a Fibonacci demonstration")
    parser.add_argument(
        "--version",
        action="version",
        version="sec_filings_api {ver}".format(ver=__version__),
    )
    parser.add_argument(
        "-v",
        "--verbose",
        dest="loglevel",
        help="set loglevel to INFO",
        action="store_const",
        const=logging.INFO,
    )
    parser.add_argument(
        "-vv",
        "--very-verbose",
        dest="loglevel",
        help="set loglevel to DEBUG",
        action="store_const",
        const=logging.DEBUG,
    )
    return parser.parse_args(args)


def setup_logging(loglevel):
    """Setup basic logging

    Args:
      loglevel (int): minimum loglevel for emitting messages
    """
    logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
    logging.basicConfig(
        level=loglevel, stream=sys.stdout, format=logformat, datefmt="%Y-%m-%d %H:%M:%S"
    )


def main(args):
    """Wrapper allowing :func:`call_api` to be called with string arguments in a CLI fashion
    Args:
      args (List[str]): command line parameters as list of strings
          (for example  ``["--verbose", "42"]``).
    """
    args = parse_args(args)
    setup_logging(args.loglevel)
    _logger.debug("Calling API...")
    print("The API result is {}".format(get()))
    _logger.info("Script ends here")


def run():
    """Calls :func:`main` passing the CLI arguments extracted from :obj:`sys.argv`

    This function can be used as entry point to create console scripts with setuptools.
    """
    main(sys.argv[1:])


if __name__ == "__main__":
    # ^  This is a guard statement that will prevent the following code from
    #    being executed in the case someone imports this file instead of
    #    executing it as a script.
    #    https://docs.python.org/3/library/__main__.html

    # After installing your project with pip, users can also run your Python
    # modules as scripts via the ``-m`` flag, as defined in PEP 338::
    #
    #     python -m sec_filings_api.skeleton 42
    #
    run()

"""
"""

import argparse
import logging
import sys
import requests

from sec_filings_api import __version__

__author__ = "paul.t.jensen"
__copyright__ = "paul.t.jensen"
__license__ = "MIT"

_logger = logging.getLogger(__name__)


# ---- Python API ----
# The functions defined in this section can be imported by users in their
# Python scripts/interactive interpreter, e.g. via
# `from sec_filings_api.skeleton import fib`,
# when using this Python module as a library.


def get():
    try:
        headers = {
            'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
        }
        session = requests.Session()
        response = session.get('https://data.sec.gov/submissions/CIK0001649339.json', timeout=5, headers=headers)
        response.raise_for_status()
        return response
    except requests.exceptions.HTTPError as errHttp:
        print(errHttp)
    except requests.exceptions.ConnectionError as errConn:
        print(errConn)
    except requests.exceptions.Timeout as errTimeout:
        print(errTimeout)
    except requests.exceptions.RequestException as errRequest:
        print(errRequest)


# ---- CLI ----
# The functions defined in this section are wrappers around the main Python
# API allowing them to be called directly from the terminal as a CLI
# executable/script.


def parse_args(args):
    """Parse command line parameters

    Args:
      args (List[str]): command line parameters as list of strings
          (for example  ``["--help"]``).

    Returns:
      :obj:`argparse.Namespace`: command line parameters namespace
    """
    parser = argparse.ArgumentParser(description="Just a Fibonacci demonstration")
    parser.add_argument(
        "--version",
        action="version",
        version="sec_filings_api {ver}".format(ver=__version__),
    )
    parser.add_argument(
        "-v",
        "--verbose",
        dest="loglevel",
        help="set loglevel to INFO",
        action="store_const",
        const=logging.INFO,
    )
    parser.add_argument(
        "-vv",
        "--very-verbose",
        dest="loglevel",
        help="set loglevel to DEBUG",
        action="store_const",
        const=logging.DEBUG,
    )
    return parser.parse_args(args)


def setup_logging(loglevel):
    """Setup basic logging

    Args:
      loglevel (int): minimum loglevel for emitting messages
    """
    logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
    logging.basicConfig(
        level=loglevel, stream=sys.stdout, format=logformat, datefmt="%Y-%m-%d %H:%M:%S"
    )


def main(args):
    """Wrapper allowing :func:`call_api` to be called with string arguments in a CLI fashion
    Args:
      args (List[str]): command line parameters as list of strings
          (for example  ``["--verbose", "42"]``).
    """
    args = parse_args(args)
    setup_logging(args.loglevel)
    _logger.debug("Calling API...")
    print("The API result is {}".format(get()))
    _logger.info("Script ends here")


def run():
    """Calls :func:`main` passing the CLI arguments extracted from :obj:`sys.argv`

    This function can be used as entry point to create console scripts with setuptools.
    """
    main(sys.argv[1:])


if __name__ == "__main__":
    # ^  This is a guard statement that will prevent the following code from
    #    being executed in the case someone imports this file instead of
    #    executing it as a script.
    #    https://docs.python.org/3/library/__main__.html

    # After installing your project with pip, users can also run your Python
    # modules as scripts via the ``-m`` flag, as defined in PEP 338::
    #
    #     python -m sec_filings_api.skeleton 42
    #
    run()

# ---- Python API ---- # The functions defined in this section can be imported by users in their # Python scripts/interactive interpreter, e.g. via # `from sec_filings_api.skeleton import fib`, # when using this Python module as a library. # ---- CLI ---- # The functions defined in this section are wrappers around the main Python # API allowing them to be called directly from the terminal as a CLI # executable/script. Parse command line parameters      Args:       args (List[str]): command line parameters as list of strings           (for example  ``["--help"]``).      Returns:       :obj:`argparse.Namespace`: command line parameters namespace Setup basic logging      Args:       loglevel (int): minimum loglevel for emitting messages Wrapper allowing :func:`call_api` to be called with string arguments in a CLI fashion     Args:       args (List[str]): command line parameters as list of strings           (for example  ``["--verbose", "42"]``). Calls :func:`main` passing the CLI arguments extracted from :obj:`sys.argv`      This function can be used as entry point to create console scripts with setuptools. # ^  This is a guard statement that will prevent the following code from #    being executed in the case someone imports this file instead of #    executing it as a script. #    https://docs.python.org/3/library/__main__.html # After installing your project with pip, users can also run your Python # modules as scripts via the ``-m`` flag, as defined in PEP 338:: # #     python -m sec_filings_api.skeleton 42 #