"""Usercentrics CMP.

URLs:
  - api.usercentrics.eu/settings/<id>/<lang>.json
  - app.usercentrics.eu/api/...
Schema: services[] with dataProcessor, dataPurpose, cookieMaxAgeSeconds
"""

import re

MATCHER = re.compile(r"(?:api|app)\.usercentrics\.eu/.+\.json(?:\?|$)", re.I)


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

    services = d.get("services") or d.get("dataProcessingServices") or []
    if not services and isinstance(d.get("settings"), dict):
        services = d["settings"].get("services") or []

    for s in services:
        name = s.get("name") or s.get("dataProcessor") or ""
        purpose = s.get("dataPurpose") or s.get("purpose") or ""
        desc = s.get("description") or ""
        country = s.get("processingCompanyCountry") or s.get("country") or ""
        max_age = s.get("cookieMaxAgeSeconds")
        retention = s.get("retentionPeriodDescription") or ""

        parts.append("")
        parts.append(f"## {name}")
        if desc:
            parts.append(desc)
        if purpose:
            parts.append(f"Zweck: {purpose}")
        if country:
            parts.append(f"Sitz: {country}")
        if max_age:
            days = max_age // 86400 if isinstance(max_age, int) else max_age
            parts.append(f"Speicherdauer: {days} Tage")
        if retention:
            parts.append(f"Aufbewahrung: {retention}")

    categories = d.get("categories") or []
    for c in categories:
        name = c.get("name") or ""
        desc = c.get("description") or ""
        parts.append("")
        parts.append(f"## Kategorie: {name}")
        if desc:
            parts.append(desc)

    return "\n".join(parts)
