# Copyright 2026, Jiri Eischmann <jiri@eischmann.cz> and the meshy contributors
# SPDX-License-Identifier: GPL-3.0-or-later

"""Pure logic extracted from RepeaterView for testability without GTK."""

ACL_ROLES = {
    3: "Admin",
    2: "Read-Write",
    1: "Read Only",
}

ROLE_PERMS = {0: 3, 1: 2, 2: 1}


def parse_acl_response(data):
    """Parse raw ACL binary response into list of {'key': hex, 'perm': int}.

    Response format: [code(1)][reserved(1)][tag(4)][payload...]
    Payload: 7-byte entries: [pubkey_prefix(6)][perm(1)]
    """
    buf = data[6:]
    entries = []
    i = 0
    while i + 7 <= len(buf):
        key = buf[i : i + 6].hex()
        perm = buf[i + 6]
        if key != "000000000000":
            entries.append({"key": key, "perm": perm})
        i += 7
    return entries


def parse_region_text(region_text, default_text=""):
    """Parse region tree text and default scope into structured data.

    Returns (entries, default_scope_name) where each entry is:
        {"name": str, "indent": int, "home": bool, "flood": bool}
    """
    default_name = ""
    if "default scope is" in default_text:
        val = default_text.split("default scope is", 1)[1].strip()
        if val and val != "<null>":
            default_name = val

    entries = []
    for line in region_text.split("\n"):
        if not line.strip():
            continue
        indent = len(line) - len(line.lstrip(" "))
        stripped = line.strip()
        flood = stripped.endswith(" F")
        if flood:
            stripped = stripped[:-2].strip()
        home = stripped.endswith("^")
        if home:
            stripped = stripped[:-1]
        entries.append(
            {
                "name": stripped,
                "indent": indent,
                "home": home,
                "flood": flood,
            }
        )
    return entries, default_name
