"""Global settings"""

import json
from pathlib import Path
from typing import Union
import yaml
from cpapis import uapi
from ._yaml import DumbYamlLoader

try:
    import paramiko as _

    HAS_PARAMIKO = True
except ImportError:
    HAS_PARAMIKO = False


def read_server_role() -> Union[tuple[None, None], tuple[str, str]]:
    """Read /etc/server.role and return imh_role, imh_class as a tuple of str"""
    try:
        server_role = Path('/etc/server.role').read_text(encoding='ascii')
    except OSError:
        imh_role, imh_class = None, None
    else:
        imh_role, imh_class = server_role.strip().split(':', maxsplit=1)
    return imh_role, imh_class


def get_secure_user(secure_fqdn: str) -> Union[str, None]:
    """Get the "secure" shared username from /etc/trueuserdomains"""
    try:
        user_domains: dict = yaml.load(
            Path('/etc/trueuserdomains').read_bytes(),
            DumbYamlLoader,
        )
    except OSError:  # If present, it's root.mail 640
        return None
    if not user_domains:
        return None
    return user_domains.get(secure_fqdn, None)


def rads_json():
    """Read rads.json"""
    # read users and groups from rads.json
    conf = json.loads(Path(__file__).parent.joinpath('rads.json').read_bytes())
    staff_groups: list[str] = conf['staff_groups']
    sys_users: list[str] = conf['sys_users']
    sys_mysql_users: list[str] = conf['sys_mysql_users']
    our_resellers: list[str] = conf['our_resellers']
    return staff_groups, sys_users, sys_mysql_users, our_resellers


def get_cpanel_extra_shared_ips() -> list[str]:
    """get any extra shared ips"""
    try:
        ipreasons = Path('/etc/reservedipreasons').read_text('ascii')
    except OSError:
        return []
    ips = []
    for line in ipreasons.splitlines():
        try:
            addr, reason = line.split('=', maxsplit=1)
        except ValueError:
            continue  # blank or malformed line
        if 'mail' in reason.lower():
            ips.append(addr.strip())
    return ips


def get_cpanel_inmotion_ips() -> list[str]:
    """get the shared inmotion ips"""
    try:
        return Path('/var/cpanel/mainips/inmotion').read_text('ascii').split()
    except OSError:
        return []


def get_secure_crt_info(secure_user: str, secure_fqdn: str) -> tuple[str, str]:
    """get the secure wildcard cert's ID and modulus"""
    if data := uapi(
        'SSL::installed_host',
        user=secure_user,
        args={'domain': secure_fqdn},
    )['result']['data']:
        return data['certificate']['id'], data['certificate']['modulus']
    raise AttributeError(f"No SSL certificates installed for {secure_user}")


def get_secure_key_file(secure_user: str, modulus: str) -> str:
    """get path to shared wildcard key"""
    if data := uapi('SSL::list_keys', secure_user)['result']['data']:
        for key_info in data:
            if key_info['modulus'] == modulus:
                key_id = key_info['id']
                return f'/home/{secure_user}/ssl/keys/{key_id}.key'
    raise AttributeError(f"No SSL keys installed for {secure_user}")
