"""What this installation is called, and what it looks like.

An instance can be somebody else's. That means four separate things, and they
are separate because they fail differently:

- an **identity** — a name, a tagline, a logo, a favicon, the icons a launcher
  shows;
- **flavour text** — the Middle-earth lines, which live in the artwork, the
  empty states, the loading lines and the error pages and nowhere else (see the
  flavour rule in the working notes), and which somebody rebranding needs to be able to
  replace without editing templates;
- **themes**, which are token sets rather than stylesheets, because the
  invariant that no component hard-codes a colour is what makes a third one
  compose at all;
- **arbitrary CSS**, for the things the first three do not reach.

## Defaults in code, overrides in the database

The prompt-fragment rule, applied again and for the same reason: text equal to
its default is never stored, so a later release improving a default still
reaches an instance whose administrator once pressed Save. `stored_only` is what
enforces it, and every save goes through it.

## Why a snapshot, and why a Jinja global

`web/templating.py:render()` has no database session, and the login page, the
error pages, the offline page and the SSE path do not go through it at all. A
context value would therefore have to be threaded through every one of those,
and the ones that bypass `render()` could not be reached at all.

So this is a **process-level cache** behind a lazy proxy registered as a Jinja
global. One query per process, and after every save; every render path gets it
including the ones that never see a `Request`. `forget()` is called by the admin
page and by nothing else.

The cost of being a cache is stated rather than discovered: with several
workers, a save in one is not seen by the others until each next reads. That is
already true of this application for other reasons -- see the "one worker" note
in the roadmap -- and this does not make it worse.
"""

from __future__ import annotations

import hashlib
import logging
import re
from dataclasses import dataclass, field
from typing import Any

from lembas.services import settings_store

log = logging.getLogger(__name__)

BRANDING = settings_store.BRANDING

DEFAULT_NAME = "LLeMbas"

# --- Flavour ------------------------------------------------------------------
# Every Middle-earth string in the interface, with its current wording as the
# default. Keyed rather than positional so a template names what it wants, and
# a key nobody has overridden costs nothing to store.
#
# The label is what the admin page calls the field; the hint says where it is
# seen, because a string with no context is one nobody can safely rewrite.
FLAVOUR: dict[str, tuple[str, str, str]] = {
    "login_tagline": (
        "Under the sign-in mark",
        "The one line on the sign-in page, beneath the name.",
        "Waybread for the long road of thought.",
    ),
    "chat_empty": (
        "Empty chat",
        "Above the composer on a chat with nothing in it yet.",
        "Speak, friend, and enter.",
    ),
    "offline_title": (
        "Offline heading",
        "The page the service worker shows when the server cannot be reached.",
        "No road from here",
    ),
    "offline_line": (
        "Offline line",
        "Beneath that heading. The sentence below it is functional and is not "
        "editable here.",
        "The Road goes ever on and on — but not without a connection.",
    ),
    "error_403": (
        "403 — not yours",
        "Shown on a page somebody is not allowed to see.",
        "Speak, friend, and enter. This door is not yours to open.",
    ),
    "error_404": (
        "404 — not found",
        "Shown on a page that does not exist.",
        "Not all those who wander are lost. This page, however, is.",
    ),
    "error_500": (
        "500 — something broke",
        "Shown when something went wrong on the server.",
        "The Road goes ever on, but this stretch of it has washed out.",
    ),
    "theme_moria": (
        "Dark theme name",
        "What the built-in dark theme is called, in the settings screen and in "
        "the /theme command.",
        "Moria",
    ),
    "theme_shire": (
        "Light theme name",
        "What the built-in light theme is called.",
        "Shire",
    ),
}

# --- Themes -------------------------------------------------------------------
# The two built-ins. `css` is empty for both: their tokens are declared in
# tokens.css, which is the one place colours live, and duplicating them here so
# that a custom theme could "inherit" would be exactly the second copy that
# rule exists to prevent. A custom theme inherits by naming a base instead --
# see `theme_css` below.
SCHEME_DARK = "dark"
SCHEME_LIGHT = "light"

BUILT_IN = (
    ("moria", SCHEME_DARK, "#101317"),
    ("shire", SCHEME_LIGHT, "#F6F1E4"),
)

# What a custom theme may set. A curated handful rather than every token a
# theme block declares: sixty colour pickers is not a feature, and everything
# left out inherits from the base, which is what makes a theme that changes
# four things four things long.
#
# `--accent-soft`, `--leaf-soft` and `--danger-soft` are deliberately absent and
# are derived instead: they are the same colour at 14% and an administrator who
# changed the accent without them would get focus rings in the old hue, which
# looks like the setting half-working.
THEME_TOKENS: tuple[tuple[str, str], ...] = (
    ("bg", "Page background"),
    ("bg-sunken", "Behind the page — the sidebar and panel gutters"),
    ("surface", "Cards, menus and the composer"),
    ("surface-raised", "Anything sitting on a surface"),
    ("surface-hover", "A surface under the pointer"),
    ("border", "Ordinary borders"),
    ("border-strong", "Borders that have to be seen"),
    ("ink", "Body text"),
    ("ink-muted", "Secondary text"),
    ("ink-faint", "Hints and timestamps"),
    ("accent", "Links, focus and interactive accents"),
    ("accent-hover", "The accent under the pointer"),
    ("accent-ink", "Text on top of the accent"),
    ("leaf", "The brand accent and the assistant's mark"),
    ("danger", "Errors and destructive actions"),
    ("success", "Confirmations and unread dots"),
    ("warning", "Warnings"),
    ("bubble-user", "Behind your own messages"),
    ("code-bg", "Behind code"),
)

THEME_TOKEN_NAMES = tuple(name for name, _ in THEME_TOKENS)

# A colour, and nothing else. Values reach a stylesheet, so a `}` in one would
# end the rule and silently break every rule after it -- and `url(…)` in a
# colour slot is a request to a third party from every page. Anything that does
# not match is dropped rather than corrected: a colour nobody can read is a
# setting that did not take, and that is visible, while a mangled one is not.
_COLOUR = re.compile(
    r"^(#[0-9a-fA-F]{3,8}"
    r"|rgba?\([0-9,.\s%/]+\)"
    r"|hsla?\([0-9,.\s%/deg]+\)"
    r"|[a-z]{3,20})$"
)

# An id that can be an attribute value and a CSS selector without quoting.
_THEME_ID = re.compile(r"^[a-z][a-z0-9-]{0,23}$")


@dataclass(frozen=True)
class Theme:
    """One theme somebody can choose."""

    id: str
    label: str
    scheme: str
    # Which built-in it starts from. A custom theme sets a handful of tokens and
    # inherits the rest, and that inheritance is a CSS fact: tokens.css matches
    # `[data-base="shire"]` as well as `[data-theme="shire"]`, so a custom light
    # theme carries `data-base="shire"` and gets the whole parchment palette
    # underneath its own four colours. Without it a light custom theme would be
    # four light colours on Moria's near-black surfaces.
    base: str = "moria"
    tokens: dict[str, str] = field(default_factory=dict)
    colour: str = ""
    built_in: bool = False


@dataclass(frozen=True)
class Branding:
    """Everything a page needs to know about whose instance this is."""

    name: str = DEFAULT_NAME
    tagline: str = ""
    logo_path: str = ""
    favicon_path: str = ""
    icon_paths: dict[str, str] = field(default_factory=dict)
    custom_css: str = ""
    text: dict[str, str] = field(default_factory=dict)
    themes: tuple[Theme, ...] = ()

    @property
    def theme_ids(self) -> tuple[str, ...]:
        return tuple(theme.id for theme in self.themes)

    @property
    def theme_list(self) -> str:
        """`id:base` pairs, space separated, for the `data-themes` attribute.

        One attribute rather than a JSON island, because two things in the
        browser need it — `/theme` validating a name, and `applyTheme` setting
        `data-base` alongside `data-theme` — and both want a list they can split
        rather than a document they have to parse.
        """
        return " ".join(f"{theme.id}:{theme.base}" for theme in self.themes)

    def theme(self, theme_id: str) -> Theme:
        for theme in self.themes:
            if theme.id == theme_id:
                return theme
        return self.themes[0]

    @property
    def revision(self) -> str:
        """A short hash of everything `/branding.css` is built from.

        It goes in that link's query string, so the URL changes exactly when the
        stylesheet does. Without it the browser's cache is the thing deciding
        when a rebrand takes effect, which is the failure this codebase keeps
        cataloguing: a save that looks like it worked and did nothing.
        """
        material = repr((self.custom_css, [(t.id, t.base, sorted(t.tokens.items())) for t in
                                           self.themes]))
        return hashlib.sha256(material.encode("utf-8")).hexdigest()[:12]


# --- Reading ------------------------------------------------------------------
def defaults() -> dict[str, Any]:
    return {
        "instance_name": "",
        "tagline": "",
        "logo_path": "",
        "favicon_path": "",
        # Derived from the logo at save time, so a launcher gets real PNGs at
        # the sizes it asks for rather than one image the browser is told to
        # scale. Empty means the shipped artwork is used.
        "icon_paths": {},
        "custom_css": "",
        "themes": [],
        **{f"text_{key}": "" for key in FLAVOUR},
    }


def _theme_from(raw: dict[str, Any]) -> Theme | None:
    """One stored custom theme, or None if it is not usable.

    Every field is validated on read rather than trusted from the row: a theme
    stored by an earlier version, or written straight into the settings table,
    still has to produce a stylesheet that parses.
    """
    theme_id = str(raw.get("id") or "").strip().lower()
    if not _THEME_ID.match(theme_id) or theme_id in {name for name, _, _ in BUILT_IN}:
        return None
    base = str(raw.get("base") or "moria")
    if base not in {name for name, _, _ in BUILT_IN}:
        base = "moria"
    tokens = {
        name: value
        for name, value in (raw.get("tokens") or {}).items()
        if name in THEME_TOKEN_NAMES and _COLOUR.match(str(value).strip())
    }
    scheme = next(s for name, s, _ in BUILT_IN if name == base)
    return Theme(
        id=theme_id,
        label=str(raw.get("label") or theme_id).strip()[:60] or theme_id,
        scheme=scheme,
        base=base,
        tokens=tokens,
        colour=tokens.get("bg", ""),
    )


def build(values: dict[str, Any]) -> Branding:
    """A snapshot from a settings group. Pure, so it can be tested without a
    database and used by the preview on the admin page."""
    text = {
        key: str(values.get(f"text_{key}") or "").strip() or default
        for key, (_, _, default) in FLAVOUR.items()
    }
    themes = [
        Theme(
            id=theme_id,
            label=text[f"theme_{theme_id}"],
            scheme=scheme,
            base=theme_id,
            colour=colour,
            built_in=True,
        )
        for theme_id, scheme, colour in BUILT_IN
    ]
    seen = {theme.id for theme in themes}
    for raw in values.get("themes") or []:
        if not isinstance(raw, dict):
            continue
        theme = _theme_from(raw)
        if theme is not None and theme.id not in seen:
            seen.add(theme.id)
            themes.append(theme)
    return Branding(
        name=str(values.get("instance_name") or "").strip() or DEFAULT_NAME,
        tagline=str(values.get("tagline") or "").strip(),
        logo_path=str(values.get("logo_path") or ""),
        favicon_path=str(values.get("favicon_path") or ""),
        icon_paths=dict(values.get("icon_paths") or {}),
        custom_css=str(values.get("custom_css") or ""),
        text=text,
        themes=tuple(themes),
    )


_CACHE: Branding | None = None


def snapshot() -> Branding:
    """The current branding, from a process-level cache.

    Never raises. An error page that cannot render because branding could not be
    read is a failure that hides the failure it was about to report, so a
    database that is not there yet answers with the defaults.
    """
    global _CACHE
    if _CACHE is not None:
        return _CACHE
    try:
        from lembas.db.session import session_scope

        with session_scope() as db:
            _CACHE = _read(db)
    except Exception:  # noqa: BLE001 - defaults are a usable answer, an exception is not
        log.debug("could not read branding; using defaults", exc_info=True)
        return build(defaults())
    return _CACHE


def _read(db) -> Branding:
    """The two groups this is assembled from.

    `instance_name` lived in the general group before there was a branding one,
    and an upgrade must not quietly rename somebody's instance back to LLeMbas.
    So the stored general value is a **seed**, and the test for it is whether the
    branding row has said anything about the name at all -- `key in row`, not
    `row[key] is truthy`. An empty stored name is somebody clearing the box,
    which has to mean the default; a *missing* one is an instance that has never
    seen this page. Reading the two the same way would resurrect the old name
    underneath a cleared one, which is the failure a cleared reasoning effort
    already documents.

    That is why this reads the raw row rather than `get_group`, which fills in
    defaults and so cannot tell absent from empty.
    """
    from lembas.db.models import Setting

    values = settings_store.get_group(db, BRANDING)
    row = db.get(Setting, BRANDING)
    said = isinstance(row, Setting) and isinstance(row.value, dict) and "instance_name" in row.value
    if not said:
        legacy = settings_store.get_group(db, settings_store.GENERAL).get("instance_name")
        if legacy:
            values = {**values, "instance_name": legacy}
    return build(values)


def forget() -> None:
    """Drop the cache. Called by the admin page's save, and by tests."""
    global _CACHE
    _CACHE = None


def for_db(db) -> Branding:
    """The snapshot, seeded from a session the caller already has open.

    Same value as `snapshot()`; this only spares the extra session on the first
    render after a restart, where one is already in hand.
    """
    global _CACHE
    if _CACHE is None:
        _CACHE = _read(db)
    return _CACHE


# --- Writing ------------------------------------------------------------------
def stored_only(values: dict[str, Any]) -> dict[str, Any]:
    """Blank anything equal to its shipped wording, so it is not an override.

    The prompt-fragment rule, and the reason it is a **blank rather than a
    dropped key**: `settings_store.update` merges, so omitting a key leaves
    whatever was stored last time. Dropping one would make "I typed the default
    back in" and "I changed nothing" store different things, and make clearing a
    box do nothing at all.

    Empty is the not-overridden marker because `build` reads `stored or
    default`. That is deliberately *not* the fragment convention, where an empty
    override means the fragment is off: a fragment being off is a state somebody
    wants, and a heading with no words is not.
    """
    return {
        key: ("" if _is_shipped(key, value) else value) for key, value in values.items()
    }


def _is_shipped(key: str, value: Any) -> bool:
    if key.startswith("text_"):
        entry = FLAVOUR.get(key[len("text_") :])
        return entry is not None and value == entry[2]
    return value == defaults().get(key)


# --- The stylesheet -----------------------------------------------------------
def _soft(colour: str, alpha: str = "0.14") -> str:
    """A colour at low opacity, for the `*-soft` tokens.

    Derived rather than asked for: they are the same colour at 14%, and an
    administrator who set an accent without them would get focus rings and
    selected states in the old hue -- which reads as the setting half-working
    rather than as a field they missed.

    Only hex is understood. Anything else answers "" and the base theme's own
    soft value stands, which is the right failure: a wrong soft colour is worse
    than an unchanged one.
    """
    value = colour.strip()
    if not value.startswith("#"):
        return ""
    digits = value[1:]
    if len(digits) == 3:
        digits = "".join(c * 2 for c in digits)
    if len(digits) not in (6, 8):
        return ""
    try:
        r, g, b = (int(digits[i : i + 2], 16) for i in (0, 2, 4))
    except ValueError:
        return ""
    return f"rgba({r}, {g}, {b}, {alpha})"


def theme_css(theme: Theme) -> str:
    """One custom theme as a rule.

    Two selectors' worth of work in one: the block sets what was chosen, and the
    `data-base` attribute on <html> is what brings the rest of the base theme's
    palette with it. Written here and served from `/branding.css`, which loads
    after `tokens.css`, so these win on order at equal specificity.
    """
    if not theme.tokens:
        return ""
    lines = [f"  --{name}: {value};" for name, value in theme.tokens.items()]
    for name, alpha in (("accent", "0.14"), ("leaf", "0.14"), ("danger", "0.14")):
        soft = _soft(theme.tokens.get(name, ""), alpha)
        if soft:
            lines.append(f"  --{name}-soft: {soft};")
    return f':root[data-theme="{theme.id}"] {{\n' + "\n".join(lines) + "\n}\n"


def stylesheet(brand: Branding) -> str:
    """Everything `/branding.css` serves.

    A route rather than an inline `<style>`, and that is a security property as
    much as a caching one: an external stylesheet has no HTML context to escape
    from, so an administrator's CSS cannot become markup however it is written.
    Inline, the same text would be one `</style>` away from being a script.
    """
    parts = [
        "/* Generated by LLeMbas from the customization settings. */",
        *(theme_css(theme) for theme in brand.themes if not theme.built_in),
    ]
    if brand.custom_css.strip():
        parts += ["/* Custom CSS. */", brand.custom_css.strip(), ""]
    return "\n".join(part for part in parts if part)


__all__ = [
    "BRANDING",
    "BUILT_IN",
    "DEFAULT_NAME",
    "FLAVOUR",
    "THEME_TOKENS",
    "THEME_TOKEN_NAMES",
    "Branding",
    "Theme",
    "build",
    "defaults",
    "for_db",
    "forget",
    "snapshot",
    "stored_only",
    "stylesheet",
    "theme_css",
]
