import socket
from pathlib import Path
from typing import Optional

from ruamel.yaml import YAML


def check_configs_empty(config_root: Path):
    config = get_configs(config_root)
    assert config == {}, f"{config_root}\n{config}"


def check_configs_default(config_dir: Path, data_dir: Path, local_config: Optional[Path] = None):
    config = get_configs(config_dir, local_config)
    truth = get_config_default_truth(config_dir, data_dir)
    # secrets are not deterministic for startup
    secrets = config["remote"].pop("secrets")
    assert secrets
    assert all(isinstance(s, bytes) for s in secrets)
    assert len(secrets) == 9
    assert config == truth, f"{config_dir}\n{config}\n{truth}"


def get_configs(config_root: Path, local_config: Optional[Path] = None):
    config = {}
    if local_config is None:
        local_config = config_root / "local.yml"
    if local_config.exists():
        config["local"] = YAML(typ="safe").load(local_config)
    remote_config = config_root / "remote.yml"
    if remote_config.exists():
        config["remote"] = YAML(typ="safe").load(remote_config)
    return config


def get_config_default_truth(config_dir: Path, data_dir: Path):
    return {
        "local": {
            "config_dir": str(config_dir),
            "data_dir": str(data_dir),
            "log_config": {
                "disable_existing_loggers": False,
                "formatters": {
                    "access": {"format": "%(asctime)s " "%(message)s"},
                    "console": {"format": "%(message)s"},
                    "standard": {
                        "format": "%(asctime)s " "%(processName)s " "[%(levelname)s] " "%(name)s: " "%(message)s"
                    },
                },
                "handlers": {
                    "access": {
                        "backupCount": 19,
                        "class": "concurrent_log_handler.ConcurrentRotatingFileHandler",
                        "encoding": "utf-8",
                        "filename": str(data_dir / "logs" / "access.log"),
                        "formatter": "access",
                        "level": "NOTSET",
                        "maxBytes": 500000,
                        "use_gzip": True,
                    },
                    "console": {
                        "class": "logging.StreamHandler",
                        "formatter": "console",
                        "level": "ERROR",
                        "stream": "ext://sys.stderr",
                    },
                    "default": {
                        "backupCount": 9,
                        "class": "concurrent_log_handler.ConcurrentRotatingFileHandler",
                        "encoding": "utf-8",
                        "filename": str(data_dir / "logs" / "process.log"),
                        "formatter": "standard",
                        "level": "NOTSET",
                        "maxBytes": 500000,
                        "use_gzip": True,
                    },
                },
                "loggers": {
                    "": {"handlers": ["default", "console"], "level": "WARNING", "propagate": False},
                    "__main__": {"handlers": ["default", "console"], "level": "DEBUG", "propagate": False},
                    "nano/access-log": {"handlers": ["access"], "level": "INFO", "propagate": False},
                    "nano/info": {"handlers": ["default"], "level": "INFO", "propagate": False},
                },
                "version": 1,
            },
            "pid_dir": str(data_dir / "pid"),
            "solr_data_dir": "data",
            "solr_dir": str(data_dir / "solr"),
            "solr_logs_dir": "logs",
            "tika_dir": str(data_dir / "tika"),
            "tika_logs_dir": "logs",
        },
        "remote": {
            "admin_password": None,
            "drives": [],
            "room_blocks": {},
            "deny_anonymous": False,
            "indexed_languages": [],
            "indexer_ignored_mimes": ["application/javascript", "text/css"],
            "name": socket.gethostname(),
        },
    }
