"""Spamcheck service configuration."""
import argparse
import os

from vyper import v

# pylint: disable=too-many-statements
def load() -> None:
    """Load the configuration options.

    Precedence for config:
        CLI arguments
        Environment variables
        Config file
        Defaults
    """

    if v.get("config_loaded"):
        return

    # Set CLI config options
    parser = argparse.ArgumentParser(description="Application settings")
    parser.add_argument(
        "--env", type=str, choices=["test", "dev", "prod"], help="Application env"
    )
    parser.add_argument("--grpc-addr", type=str, help="Application bind address")
    parser.add_argument(
        "--log-level",
        type=str,
        choices=["debug", "info", "warning", "error", "fatal"],
        help="Application log level",
    )
    parser.add_argument(
        "--ml-classifiers", type=str, help="Directory location for ML classifiers"
    )
    parser.add_argument("--gcs-bucket", type=str, help="Bucket to save spammable data for labeling")
    parser.add_argument("--google-pubsub-project", type=str, help="Google PubSub project")
    parser.add_argument("--google-pubsub-topic", type=str, help="Google PubSub topic")
    parser.add_argument("--tls-certificate", type=str, help="TLS certificate path")
    parser.add_argument("--tls-private-key", type=str, help="TLS private key path")
    parser.add_argument("-c", "--config", type=str, help="Path to config file")

    parser.add_argument("--max-generic-verdict", type=str, help="Maximum verdict for generics")
    parser.add_argument("--max-issue-verdict", type=str, help="Maximum verdict for issues")
    parser.add_argument("--max-snippet-verdict", type=str, help="Maximum verdict for snippets")

    # ignore unknown args. These will be present when running unit tests
    args, _ = parser.parse_known_args()
    v.bind_args(args.__dict__)

    # Set config file options
    v.set_config_type("yaml")
    v.set_config_name("config")
    v.add_config_path("./config")

    # Set environment variable options
    v.set_env_prefix("spamcheck")
    v.automatic_env()

    # Set defaults
    v.set_default("env", "development")
    v.set_default("grpc_addr", "0.0.0.0:8001")
    v.set_default("log_level", "info")
    v.set_default("google_pubsub_topic", "spamcheck")
    v.set_default("tls_certificate", "./ssl/cert.pem")
    v.set_default("tls_private_key", "./ssl/key.pem")
    v.set_default("ml_classifiers", "./classifiers")
    v.set_default("filter.allow_list", {})
    v.set_default("filter.deny_list", {})
    v.set_default("filter.allowed_domains", [])

    v.set_default("max_generic_verdict", "ALLOW")
    v.set_default("max_issue_verdict", "CONDITIONAL_ALLOW")
    v.set_default("max_snippet_verdict", "CONDITIONAL_ALLOW")

    # Load config file
    config_file = None
    if args.config:
        config_file = args.config
    elif v.is_set("config"):
        config_file = v.get_string("config")
    if config_file:
        with open(config_file, encoding="utf-8") as handle:
            config_data = handle.read()
        v.read_config(config_data)
    else:
        try:
            v.read_in_config()
        except FileNotFoundError:
            pass

    if os.path.exists(v.get("tls_private_key")) and os.path.exists(
        v.get("tls_certificate")
    ):
        v.set("tls_enabled", True)

    v.set("config_loaded", True)
