#
# Copyright (C) 2019-Present A-Team Digital Solutions
#

import os
import shlex
from configparser import ConfigParser

def load_hosts(
    config_file="configs/hosts.conf"
):
    config = ConfigParser()
    config.read(config_file)
    hosts = []
    for section in config.sections():
        if section == "Local":
            hosts.append(section)
            continue
        host = config.get(
            section,
            "server_address",
            fallback=""
        ).strip()
        if host:
            hosts.append(section)
    return hosts
def get_host_config(
    host_name,
    config_file="configs/hosts.conf"
):
    config = ConfigParser()
    config.read(config_file)
    if host_name not in config:
        return None
    return dict(config[host_name])
def build_ssh_args(cfg):
    """
    Build SSH arguments from a host configuration.
    Returns:
        [
            "ssh",
            "-i",
            "/home/user/.ssh/id",
            "-p",
            "22",
            "user@host"
        ]
    """
    server = cfg["server_address"]
    user = cfg["user"]
    port = str(cfg.get("port", "22"))
    args = ["ssh"]
    ssh_options = cfg.get("ssh_options", "").strip()
    if ssh_options:
        expanded = os.path.expanduser(ssh_options)
        args.extend(shlex.split(expanded))
    args.extend([
        "-p",
        port,
        f"{user}@{server}"
    ])
    return args
def build_ssh_command(cfg):
    """
    Return SSH command as a shell string.
    """
    return " ".join(build_ssh_args(cfg))
