import os
from pathlib import Path

from clarabot_nano.utility.path.common import normalize_validate_resolve_absolute_path


def writable_directory(path: str) -> bool:
    os.makedirs(path, mode=0o700, exist_ok=True)
    return os.access(path, os.W_OK)


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"])
