"""aspnet_Profile：PropertyNames 形如 'Name:S:起点:长度:'；ExpandAttribute 为 DataContract 序列化的字典。"""
import html
import re

_PAIR = re.compile(r"<Key>(.*?)</Key>\s*<Value[^>]*>(.*?)</Value>", re.S)


def parse_profile(names: str | None, values: str | None) -> dict[str, str]:
    parts, values, props = (names or "").split(":"), values or "", {}
    for i in range(0, len(parts) - 3, 4):
        name, kind, start, length = parts[i:i + 4]
        if kind == "S" and start.isdigit() and length.lstrip("-").isdigit() and int(length) >= 0:
            props[name] = values[int(start):int(start) + int(length)]
    return props


def parse_expand_attributes(xml: str | None) -> dict[str, str]:
    return {html.unescape(k): html.unescape(v) for k, v in _PAIR.findall(xml or "")}
