import re
#!/usr/bin/env python3
"""Shared .brand pack parsing — importable WITHOUT executing the engine.

The engine, slicer, and QR tool all read packs through this one parser so the
format has a single definition.
"""


def parse_pack(path):
    """Parse a bash-style KEY="value" pack file (same family as .pack files)."""
    out = {}
    with open(path, "r", encoding="utf-8") as f:
        for raw in f:
            line = raw.strip()
            if not line or line.startswith("#"):
                continue
            if "=" not in line:
                continue
            key, _, val = line.partition("=")
            key = key.strip()
            val = val.strip()
            # A quoted value may be followed by a comment, which bash strips when it sources
            # the pack and this parser did not: QR_URL="https://labs.google/flow/about"  # note
            # came back WITH its quotes, so every URL check compared '"x"' against 'x' and the
            # lint refused a good pack (2026-08-31, the first product URL that had a path).
            m = re.match(r"""^("[^"]*"|'[^']*')\s*(?:#.*)?$""", val)
            if m:
                val = m.group(1)[1:-1]
            else:
                val = val.split(" #")[0].strip()
            out[key] = val
    return out


def hex_rgb(v, fallback=None):
    v = (v or "").lstrip("#")
    if len(v) != 6:
        if fallback is None:
            raise SystemExit(f"pack: bad hex colour {v!r}")
        return fallback
    return tuple(int(v[i:i + 2], 16) for i in (0, 2, 4))
