"""TrustArc / TRUSTe CMP.

URLs:
  - consent.trustarc.com/v2/notice/<id>
  - cookie-pref.trustarc.com/...
Schema varies; typically categories[] + vendors[]
"""

import re

MATCHER = re.compile(
    r"(?:consent|cookie-pref|tr-cdn)\.trustarc\.com/.+\.(?:json|js)(?:\?|$)", re.I,
)


def reconstruct(d: dict) -> str:
    parts: list[str] = ["# Cookie-Richtlinie (TrustArc)"]

    for key in ("title", "summary", "description", "intro"):
        v = d.get(key)
        if v:
            parts.append("")
            parts.append(str(v))

    cats = d.get("categories") or d.get("Categories") or []
    for c in cats:
        name = c.get("name") or c.get("Name") or ""
        desc = c.get("description") or c.get("Description") or ""
        parts.append("")
        parts.append(f"## {name}")
        if desc:
            parts.append(str(desc))
        cookies = c.get("cookies") or c.get("Cookies") or []
        for ck in cookies[:50]:
            cn = ck.get("name") or ck.get("Name") or ""
            cp = ck.get("purpose") or ck.get("Purpose") or ""
            ce = ck.get("expires") or ck.get("Expires") or ""
            line = f"- {cn}"
            if cp:
                line += f" — {cp[:120]}"
            if ce:
                line += f" — Speicherdauer: {ce}"
            parts.append(line)

    vendors = d.get("vendors") or d.get("Vendors") or []
    if vendors:
        parts.append("")
        parts.append(f"## Anbieter ({len(vendors)})")
        for v in vendors[:80]:
            name = v.get("name") or v.get("Name") or ""
            parts.append(f"- {name}")

    return "\n".join(parts)
