"""Reading a reference: a picture of a piece the owner likes becomes a design in the vocabulary, by one look of the
model, checked by code. The model says what it saw in the picture and what the picture does that the blocks and words
cannot say; code checks only that the answer is a valid template. What the product then has to change to fit the
journey is added to that list by the product, so what the owner reads is true to what was built. The model call is a
function the product passes in (it shows the picture)."""
from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List

from .decide import _plain, vocabulary_lines
from .load import template_from_dict
from .spec import Template

Ask = Callable[[str, str], dict]

SYSTEM = """You are looking at a picture of an email the owner likes, as a reference for the design of a new one. Read its
composition and mood and say it in the given blocks, looks and style words: which sections it stacks in what order, how
much air, how large the heading, where the picture and the button sit, light or dark, serif or sans. The brand will be the
owner's and the words and values will be the new journey's, so read the layout, not the content: do not copy its words,
its product or its colours. Answer with the template (name, kind, description, style, blocks with looks), `saw`: what the
picture does, in plain words, and `could_not`: what it does that these blocks and words cannot say, in plain words, so the
owner is told. Use only the blocks, looks and style words given."""


@dataclass
class Read:
    template: Template
    saw: List[str] = field(default_factory=list)
    could_not: List[str] = field(default_factory=list)
    tried: List[str] = field(default_factory=list)


def read_reference(ask: Ask, channel: str = "email") -> Read:
    """`ask(system, user)` shows the picture and returns the model's answer as a dict with template fields plus
    `saw` and `could_not`. The picture is read on its own, without the brief; an answer that is not a valid template
    goes back once with the reason."""
    # The picture alone: shown the brief and the brand's values as well, the model designed for them and called it a
    # read (a product grid "seen" in a picture with none). Fitting the read to the journey is the director's step.
    user = "Read the picture into these blocks, looks and style words.\n\n" + vocabulary_lines()
    tried: List[str] = []
    answer: Dict[str, Any] = {}
    for _ in range(2):
        answer = ask(SYSTEM, user) or {}
        data = {k: v for k, v in answer.items() if k not in ("saw", "could_not")}
        data.setdefault("channel", channel)
        data.setdefault("kind", "custom")
        data.setdefault("name", "From the owner's reference")
        data.setdefault("description", "Read from a picture the owner gave as the reference.")
        data["owner"] = "organisation"
        try:
            template = template_from_dict(data)
        except (ValueError, KeyError, TypeError) as exc:
            why = _plain(exc)
            tried.append(why)
            user += f"\n\nYour last answer cannot be used: {why}. Answer again."
            continue
        return Read(template, [str(s) for s in answer.get("saw") or []], [str(s) for s in answer.get("could_not") or []], tried)
    raise ValueError("the reference could not be read into a design: " + "; ".join(tried))


__all__ = ["Read", "read_reference", "SYSTEM"]
