"""The product's brand name, from its one source: aventurro/brand.json (AV-013).

The working name is a test name that may still change, so nothing else in
the code base spells it out. ``BRAND_NAME`` in the environment overrides the
displayed name (to try another one without editing anything); the slug --
which settings keys are built from -- only ever comes from the file, so
trying a name never moves anyone's saved settings. ``BRAND_DOMAIN`` is the
domain once there is one (none is written anywhere until then).

"Mountain Twin" is the engine and repository name, not the brand, and is not
affected by any of this."""

from __future__ import annotations

import json
import os
import re
from pathlib import Path
from typing import Any

BRAND_FILE = Path(__file__).resolve().parents[1] / "aventurro" / "brand.json"


def drawing(path: Path) -> dict[str, Any]:
    """An SVG of the logo (AV-046: aventurro/assets/brand/lentiqa/, built by
    scripts/build_lentiqa_brand.py) as the page draws it inline: its viewBox
    and its inner markup -- gradients with "lq-" ids that
    aventurro/brand_runtime.js numbers per copy on the page, the clouds
    (.lq-cloud) and, in the full logo, each letter's group (.brand-letter,
    data-letter), which the intro animates one by one."""
    svg = path.read_text(encoding="utf-8")
    return {
        "viewBox": re.search(r'viewBox="([^"]+)"', svg).group(1),
        "markup": re.search(r"<svg[^>]*>(.*)</svg>", svg, re.S).group(1),
        "letters": re.findall(r'class="brand-letter" data-letter="([^"]+)"', svg),
    }


def brand(environ: dict[str, str] | None = None) -> dict[str, Any]:
    environ = os.environ if environ is None else environ
    stored = json.loads(BRAND_FILE.read_text(encoding="utf-8"))
    name = (environ.get("BRAND_NAME") or "").strip() or stored["name"]
    drawn = stored.get("logotype") if stored.get("logotype_name") == name else None
    return {
        # The whole logo (clouds + the name's letters), or None for another
        # name -- then the page draws the clouds (symbol) and the name as text.
        "logotype": drawing(BRAND_FILE.parents[1] / drawn) if drawn else None,
        "symbol": drawing(BRAND_FILE.parents[1] / stored["symbol"]),
        "name": name,
        "nameUpper": name.upper(),
        "slug": stored["slug"],
        "tagline": stored["tagline"],
        "domain": (environ.get("BRAND_DOMAIN") or "").strip(),
        "previousSlugs": list(stored.get("previous_slugs", [])),
    }


def brand_script(environ: dict[str, str] | None = None) -> str:
    """The brand as the page's first script (/aventurro/brand.js): a frozen
    ``window.BRAND`` read synchronously, so the tab title and every label
    are right from the first paint."""
    return "window.BRAND = Object.freeze(%s);\n" % json.dumps(brand(environ), ensure_ascii=False)
