import subprocess
from helpers.container import exec_in_container

def read_file(container_name, path):
    """Return content of a file."""
    result = exec_in_container(container_name, ["cat", path])
    if result.returncode != 0:
        raise RuntimeError(f"Cannot read {path} in {container_name}: {result.stderr}")
    return result.stdout

def write_file(container_name, path, content):
    """Write content to a file."""
    cmd = ["sh", "-c", f"echo '{content}' | tee {path}"]
    result = exec_in_container(container_name, cmd)
    if result.returncode != 0:
        raise RuntimeError(f"Cannot write {path} in {container_name}: {result.stderr}")


# UCI helpers
# -----------

def config_read(container, configfile):
    """Return dictionary of sections with options from UCI config."""
    result = exec_in_container(container, ["uci", "show", configfile])
    if result.returncode != 0:
        raise RuntimeError(f"Cannot read UCI config {configfile}: {result.stderr}")
    uci_dict = {}
    for line in result.stdout.splitlines():
        # Example: wifi.@device[0].macaddr='b0:b0:b0:00:00:01'
        if '=' not in line:
            continue
        key, value = line.split('=', 1)
        key_parts = key.split('.')
        section = key_parts[1]  # e.g., @device[0]
        option = key_parts[2] if len(key_parts) > 2 else None
        value = value.strip("'\"")
        if section not in uci_dict:
            uci_dict[section] = {}
        if option:
            uci_dict[section][option] = value
    return uci_dict


def config_set(container, configfile, section, option, value):
    """Set a UCI option."""
    cmd = ["uci", "set", f"{configfile}.{section}.{option}={value}"]
    result = exec_in_container(container, cmd)
    if result.returncode != 0:
        raise RuntimeError(f"Failed to set {option}={value} in {section} of {configfile}: {result.stderr}")

def config_get(container, configfile, section, option):
    """Get a UCI option value."""
    cmd = ["uci", "get", f"{configfile}.{section}.{option}"]
    result = exec_in_container(container, cmd)
    if result.returncode != 0:
        raise RuntimeError(f"Failed to get {option} in {section} of {configfile}: {result.stderr}")
    return result.stdout.strip()


def config_commit(container, configfile):
    """Commit changes to a UCI config."""
    result = exec_in_container(container, ["uci", "commit", configfile])
    if result.returncode != 0:
        raise RuntimeError(f"Failed to commit {configfile}: {result.stderr}")


def config_delete(container, configfile, section, option=None):
    """
    Delete a section or an option in UCI config.
    - If option is None, deletes the whole section.
    - Otherwise deletes the specific option.
    """
    if option:
        cmd = ["uci", "delete", f"{configfile}.{section}.{option}"]
    else:
        cmd = ["uci", "delete", f"{configfile}.{section}"]
    result = exec_in_container(container, cmd)
    if result.returncode != 0:
        raise RuntimeError(f"Failed to delete {option if option else section} in {configfile}: {result.stderr}")

