"""A content template as data: which blocks, in what order, with what style, and what each block needs.

A template owns the layout and nothing else. No words, no colour, no font, no logo: those are values, filled by
whoever knows them (see values.py). The same file serves every organisation and every piece of content of its kind.
"""
from __future__ import annotations

from typing import Any, Dict, List, Literal, Optional

from pydantic import BaseModel, Field, model_validator

Channel = Literal["email", "sms", "push", "card", "post"]
Source = Literal["brand", "journey", "audience", "behaviour", "identity", "copy", "made"]
Kind = Literal["text", "image", "url", "money", "list", "colour"]


class Value(BaseModel):
    """One thing a block shows. `source` says who knows it; identity and behaviour values may be filled per person
    at send time, the rest when the content is written."""
    key: str
    source: Source
    kind: Kind = "text"
    required: bool = True
    max_words: Optional[int] = None
    max_chars: Optional[int] = None
    event: Optional[str] = None          # behaviour: the event whose captures carry it, e.g. add_to_cart
    fallback: Optional[str] = None       # identity: what the sender writes when the person has no value


class Block(BaseModel):
    type: str
    name: Optional[str] = None                           # set when a type repeats: two buttons, three products
    values: List[Value] = Field(default_factory=list)   # the block type's contract, overridable per template
    options: Dict[str, str] = Field(default_factory=dict)  # e.g. ratio "2:1", show "image,name,price"


class Style(BaseModel):
    """The composition. Every token is a word a renderer turns into layout; none is a colour or a font."""
    align: Literal["left", "center"] = "left"
    ground: Literal["white", "tinted", "warm", "brand"] = "tinted"   # brand: a light tint of the brand's own colour
    frame: Literal["card", "flat"] = "card"
    radius: Literal["none", "soft", "round"] = "soft"
    button: Literal["filled", "outline", "pill", "link"] = "filled"
    heading: Literal["small", "large", "display"] = "large"
    density: Literal["airy", "regular", "compact"] = "airy"
    hero: Literal["none", "inset", "bleed"] = "inset"
    rules: Literal["none", "thin", "strong"] = "none"
    columns: Literal["one", "two"] = "one"
    type: Literal["sans", "serif"] = "sans"   # the pairing drawn when the brand has no measured fonts, or when fonts = template
    fonts: Literal["brand", "template"] = "brand"   # template: the pairing wins even over measured brand fonts (the owner asked)
    logo: Literal["small", "large"] = "small"


class Template(BaseModel):
    name: str
    channel: Channel
    kind: str                              # offer, product, welcome, confirmation, reminder, follow_up, feedback, newsletter, cart
    description: str                       # one sentence; what the pick is made from
    suits: List[str] = Field(default_factory=list)
    style: Style = Field(default_factory=Style)
    blocks: List[Block]
    sample: Dict[str, Any] = Field(default_factory=dict)   # example values for a gallery preview, never for a real send
    version: int = 1
    owner: Literal["galaxiq", "organisation"] = "galaxiq"

    @model_validator(mode="after")
    def _one_of_each_required(self) -> "Template":
        if not self.blocks:
            raise ValueError("a template holds at least one block")
        # Words are written once and shown once: the same headline on two blocks is a repeat. A fact may be shown twice
        # (the link on a banner and on the button at the end, the brand's name in the header and the footer).
        words = [v.key for b in self.blocks for v in b.values if v.source == "copy" and v.key != "copy.cta_label"]
        twice = sorted({k for k in words if words.count(k) > 1})
        if twice:
            raise ValueError(f"a value is filled once; {', '.join(twice)} appear on two blocks: name the repeated block")
        return self

    def values(self) -> List[Value]:
        return [v for b in self.blocks for v in b.values]

    def needs(self) -> List[str]:
        """What an organisation must have for this template, in words: the required values that are not copy and
        not the brand (every organisation has a name; a logo is never required)."""
        said = []
        for v in self.values():
            if not v.required or v.source in ("copy", "brand", "made"):
                continue
            if v.source == "behaviour" and v.event:
                said.append(f"the {v.event} event firing")
            elif v.source == "identity":
                said.append("people you know by name")
            else:
                first, last = v.key.split(".", 1) if "." in v.key else ("", v.key)
                last = "link" if last == "url" else last.replace("_", " ")
                thing = last if first in ("", "cta") else f"{first} {last}"
                said.append(f"{'an' if thing[0] in 'aeiou' else 'a'} {thing} on the journey")
        return list(dict.fromkeys(said))
