"""What each block type shows, as its default values. A template may mark any of them optional or required; it may
not invent a value a block has no place for. A renderer for a channel draws the block types it supports."""
from __future__ import annotations

from typing import Dict, List

from .spec import Block, Value

CONTRACT: Dict[str, List[Value]] = {
    "header": [Value(key="brand.logo", source="brand", kind="image", required=False),
               Value(key="brand.name", source="brand")],
    "hero": [Value(key="made.hero_image", source="made", kind="image", required=False)],
    "greeting": [Value(key="person.first_name", source="identity", required=False, fallback="there")],
    "heading": [Value(key="copy.headline", source="copy", max_words=9),
                Value(key="copy.eyebrow", source="copy", required=False, max_words=4)],
    # a coloured section with the headline, a line under it and the button inside it: the statement the email opens with
    "banner": [Value(key="copy.headline", source="copy", max_words=8),
               Value(key="copy.eyebrow", source="copy", required=False, max_words=4),
               Value(key="copy.lede", source="copy", required=False, max_words=24),
               Value(key="copy.cta_label", source="copy", required=False, max_words=4),
               Value(key="cta.url", source="journey", kind="url", required=False)],
    "text": [Value(key="copy.body", source="copy", kind="list", max_words=90)],
    "product": [Value(key="product.name", source="journey"),
                Value(key="product.image", source="journey", kind="image", required=False),
                Value(key="product.price", source="journey", kind="money", required=False),
                Value(key="product.currency", source="journey", required=False),
                Value(key="product.url", source="journey", kind="url", required=False)],
    "cart": [Value(key="cart.items", source="behaviour", kind="list", event="add_to_cart"),
             Value(key="cart.total", source="behaviour", kind="money", required=False, event="add_to_cart"),
             Value(key="cart.url", source="journey", kind="url")],
    "offer": [Value(key="offer.code", source="journey"),
              Value(key="offer.line", source="copy", required=False, max_words=12)],
    # label/value rows (When, Where, Bring): written from what the brief states, never from anywhere else
    "facts": [Value(key="facts.rows", source="copy", kind="list")],
    "button": [Value(key="copy.cta_label", source="copy", max_words=4),
               Value(key="cta.url", source="journey", kind="url")],
    "divider": [],
    "footer": [Value(key="brand.name", source="brand"),
               Value(key="brand.address", source="brand", required=False),
               Value(key="brand.social", source="brand", kind="list", required=False)],
    # several products across: the items are the journey's or the catalogue's, two or three per row (option `across`)
    "grid": [Value(key="grid.items", source="journey", kind="list")],
    # the same products one per row, picture beside words, sides alternating: the long-form product story
    "features": [Value(key="grid.items", source="journey", kind="list")],
    # a real customer's words, given by the owner; never written by the copy model
    "quote": [Value(key="quote.text", source="journey", max_words=60),
              Value(key="quote.by", source="journey", required=False, max_words=8)],
    # two columns of words side by side, for a comparison or two short sections
    "columns": [Value(key="columns.left_heading", source="copy", required=False, max_words=6),
                Value(key="columns.left", source="copy", kind="list", max_words=60),
                Value(key="columns.right_heading", source="copy", required=False, max_words=6),
                Value(key="columns.right", source="copy", kind="list", max_words=60)],
    # the sign-off: who it is from, the brand mark, the brand's social links
    "signature": [Value(key="signature.name", source="copy", max_words=6),
                  Value(key="brand.logo", source="brand", kind="image", required=False),
                  Value(key="brand.social", source="brand", kind="list", required=False)],
}


# The look a block may be given, beyond the template's style: each a word a renderer turns into drawing. A design
# chooses per block, so two emails from one block list rarely look alike.
LOOK = {
    "size": ("small", "regular", "large", "display"),        # headings and text scale
    "weight": ("light", "regular", "bold"),
    "align": ("left", "center"),
    "surface": ("flat", "card", "band", "tint"),             # what the block sits on
    "space": ("tight", "regular", "loose"),                  # room above and below
    "image": ("inset", "bleed", "round", "framed", "small"),  # how a picture is treated
    "accent": ("none", "text", "surface", "rule"),           # where the brand's accent lands in this block
    "rule": ("none", "thin", "strong"),
    "colour": ("primary", "accent", "ink"),                  # which of the brand's colours this block's accent uses
}
# Options a block takes beyond its looks, by type. Anything else in a block's dict is a value the model put in the
# wrong place (brand.logo: true, cta.url: ...); it carries nothing a block can draw and is left off. Refusing it
# cost whole emails: a model told twice still wrote them, and the plain note stood in.
OPTIONS = {"grid": ("across",), "hero": ("ratio",), "product": ("show",), "features": ("numbered",)}

# What each block is for, in a line, for the model that lays an email out.
ABOUT = {
    "header": "the brand mark at the top", "hero": "the picture made for this email", "greeting": "Hi, by name",
    "heading": "the headline, with an optional small label above it", "text": "the paragraphs",
    "banner": "a coloured section holding the headline, a line under it and the button: the statement the email opens or closes with",
    "product": "one product with its picture and price", "cart": "what they left in the cart, as a receipt",
    "offer": "the code, as a chip or on a band", "facts": "label and value rows for details the brief states",
    "button": "the one call to action", "divider": "space or a rule between sections", "footer": "name, address, social links, unsubscribe",
    "grid": "two or three products per row as cards with name, price and a Shop link",
    "features": "the products one per row, picture beside words, sides alternating, numbered when asked; the same products as grid, so a design uses grid or features, not both",
    "quote": "a customer's own words", "columns": "two columns of words", "signature": "the sign-off",
}


def block(type_: str, **overrides) -> Block:
    """A block of a known type with its contract. optional=[...] and required=[...] change a value's standing;
    name="second" lets a type repeat under its own keys; anything else is an option for the renderer."""
    if type_ not in CONTRACT:
        raise ValueError(f"no block type {type_!r}; known: {', '.join(CONTRACT)}")
    optional = set(overrides.pop("optional", []) or [])
    required = set(overrides.pop("required", []) or [])
    unknown = (optional | required) - {v.key for v in CONTRACT[type_]}
    if unknown:
        raise ValueError(f"{type_} has no value {', '.join(sorted(unknown))}")
    name = overrides.pop("name", None)
    for key, word in list(overrides.items()):
        if key in LOOK and str(word) not in LOOK[key]:
            raise ValueError(f"{type_}: {key} may be {', '.join(LOOK[key])}, not {word!r}")
        if key not in LOOK and key not in OPTIONS.get(type_, ()):
            overrides.pop(key)
    values = []
    for v in CONTRACT[type_]:
        must = False if v.key in optional else True if v.key in required else v.required
        # A repeated block is named, and its values live under that name: a second product block named "second"
        # reads second.name, second.image. The source and the kind stay the type's own.
        key = f"{name}.{v.key.split('.', 1)[1]}" if name and "." in v.key and not v.key.startswith("brand.") else v.key
        values.append(v.model_copy(update={"required": must, "key": key}))
    return Block(type=type_, name=name, values=values, options={k: str(v) for k, v in overrides.items()})


def known_types() -> List[str]:
    return list(CONTRACT)
