from pathlib import Path

from clarabot_nano_common.config.utility import writable_directory
from clarabot_nano_common.utility.path.common import normalize_validate_resolve_absolute_path

from clarabot_nano.utility.network import DYNAMIC_SERVICE_PORT_RANGE


def valid_custom_service_port(port: int) -> bool:
    return 0 < port < DYNAMIC_SERVICE_PORT_RANGE[0] or DYNAMIC_SERVICE_PORT_RANGE[1] < port < 65536


def abs_or_base_rel_directory(spec: str, base: str) -> Path:
    p = Path(spec)
    if not p.is_absolute():
        p = Path(base, spec)
    if not writable_directory(str(p)):
        raise Exception(f"Dependency data directory is not writable: {p}")
    return normalize_validate_resolve_absolute_path(p)


def config_get_pid_dir(config: dict) -> Path:
    return abs_or_base_rel_directory(config["local"]["pid_dir"], config["local"]["data_dir"])


def config_get_solr_data_dir(config: dict) -> Path:
    return abs_or_base_rel_directory(config["local"]["solr_data_dir"], config["local"]["solr_dir"])


def config_get_solr_logs_dir(config: dict) -> Path:
    return abs_or_base_rel_directory(config["local"]["solr_logs_dir"], config["local"]["solr_dir"])


def config_get_tika_logs_dir(config: dict) -> Path:
    return abs_or_base_rel_directory(config["local"]["tika_logs_dir"], config["local"]["tika_dir"])
