"""The composition: from the design brief, the model lays the piece out. It sees the brief it wrote, the owner's
words, the facts in hand, every template on the shelf with whether it fits and why not, and the blocks, the looks a
block may take and the style words. It answers with one of three things and a reason: use a shelf template as it
is, adapt one (blocks added, removed, reordered, given looks; style changed), or design a new one from the blocks.
No order between the three and no gate: the brief and the facts decide.

Code checks only reality: the answer is a valid template (known blocks, looks and style words, values that exist)
and it fits the facts in hand. An answer that fails goes back once with the reason. After that the plainest fitting
template stands in and says what could not be made. The model call is a function the product passes in."""
from __future__ import annotations

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

from .blocks import ABOUT, CONTRACT, LOOK
from .load import template_from_dict
from .spec import Style, Template
from .values import Fit, Values, fit

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

SYSTEM = """You lay out one piece of content from the design brief you wrote for it. You are given that brief, the
owner's own words about the design if they said anything, what is known about the brand, the audience and the
facts in hand, what this owner kept before, every template on the shelf with one line on what it is for, its blocks,
and whether it can be filled right now and why not, and the blocks a design may use with the looks each may take
and the style words for the whole.

Answer with exactly one of three actions, as JSON:
- {"action": "use", "name": "<template>", "reason": "<one sentence>"}: a shelf template realises the brief as it is.
- {"action": "adapt", "name": "<template>", "changes": {"blocks": [<full block list>] or null, "style": {<style words
  to change>} or null}, "reason": "<one sentence>"}: a shelf template is the right start but the brief calls for
  blocks added, removed, reordered or given looks, or a different composition.
- {"action": "design", "template": {"name": "<short name>", "kind": "<kind>", "description": "<one sentence>",
  "style": {...}, "blocks": [<block list>]}, "reason": "<one sentence>"}: nothing on the shelf resembles what the
  brief asks for; compose it from the blocks.

A block in a list is a type name, or an object with its type and its looks, for example:
["header", {"type": "heading", "size": "display", "colour": "primary"}, "text", {"type": "offer", "surface": "band"},
{"type": "button", "space": "loose", "colour": "primary"}, {"type": "product", "name": "second", "optional":
["product.url"]}, "footer"]. A block's object holds only its type, a name when the type repeats, "optional" for
values it may go without, and look words; never a value (no brand.logo, no cta.url: those are facts in hand).
Give a block a look when the brief calls for it: a display heading, a band for the offer, a loose space before the
button, the primary colour on the button. Use only the block types, look words and style words given. Never choose
a template that cannot be filled; never add a block whose required values are not in hand unless you mark them
optional. The owner's own choice stands when it can be filled. Say only what the brief says: show products, a
cart, a quote or a picture only when the brief or the owner's words are about them. The reason is in the owner's
words and names what in the brief made you lay it out this way."""


@dataclass
class Decision:
    template: Template
    action: str                                   # use | adapt | design | stand_in
    reason: str
    based_on: Optional[str] = None                # the shelf template an adaptation started from
    tried: List[str] = field(default_factory=list)   # answers that failed, with why, in order
    fallback: bool = False


def decide(templates: Dict[str, Template], brief: str, values: Values, fired: Dict[str, bool], ask: Ask,
           owner_words: str = "", known: str = "", channel: str = "email", stand_in: str = "Note",
           design: str = "", taste: str = "", check: Optional[Callable[[Template], Optional[str]]] = None) -> Decision:
    """`check` is the product's own look at a chosen design (a fact of the account the library cannot know): a reason
    it returns is sent back to the model like a value that cannot be filled."""
    fits = {name: fit(t, values) for name, t in templates.items()}
    user = _user_prompt(templates, fits, fired, brief, owner_words, known, channel, design, taste)
    tried: List[str] = []
    for _ in range(2):
        answer = ask(SYSTEM, user) or {}
        try:
            template, action, based_on = _template_from(answer, templates, channel)
            f = fit(template, values)
            if not f.ok:
                raise ValueError(f.why_not(fired))
            if values.has("cta.url") and not any(b.type == "button" for b in template.blocks):
                # The step carries a link the owner gave; a design with no button leaves it going nowhere.
                raise ValueError("the step has a button link but this design has no button block, so the link would go nowhere; keep a button")
            refused = check(template) if check else None
            if refused:
                raise ValueError(refused)
            return Decision(template, action, str(answer.get("reason") or "").strip(), based_on, tried)
        except (ValueError, KeyError, TypeError) as exc:
            why = _plain(exc)
            named = answer.get("name") or (answer.get("template") or {}).get("name") or ""
            tried.append(f"{answer.get('action', '?')} {named}: {why}".strip())
            user += f"\n\nYour last answer cannot be used: {why}. Answer again."
    usable = [n for n, f in fits.items() if f.ok]
    if not usable:
        raise ValueError("no template can be filled: " + "; ".join(f.why_not(fired) for f in fits.values()))
    name = stand_in if stand_in in usable else usable[0]
    last = tried[-1].split(": ", 1)[-1] if tried else "no answer"
    return Decision(templates[name], "stand_in", f"{name} stands in; what was asked for could not be made: {last}", None, tried, fallback=True)


def _template_from(answer: dict, templates: Dict[str, Template], channel: str):
    action = str(answer.get("action") or "").lower()
    if action == "use":
        return _named(templates, answer.get("name")), "use", None
    if action == "adapt":
        base = _named(templates, answer.get("name"))
        changes = answer.get("changes") or {}
        data = base.model_dump()
        data["name"] = f"{base.name}, adapted"
        data["owner"] = "organisation"
        if changes.get("style"):
            data["style"] = {**data["style"], **{k: v for k, v in changes["style"].items() if k in Style.model_fields}}
        data["blocks"] = changes.get("blocks") or [block_as_written(b) for b in base.blocks]
        return template_from_dict(data), "adapt", base.name
    if action == "design":
        data = dict(answer.get("template") or {})
        data.setdefault("channel", channel)
        data.setdefault("kind", "custom")
        data.setdefault("description", str(answer.get("reason") or "A design made for this piece."))
        data["owner"] = "organisation"
        return template_from_dict(data), "design", None
    raise ValueError(f"the action must be use, adapt or design, not {action!r}")


def _named(templates: Dict[str, Template], name: Any) -> Template:
    want = str(name or "").strip().lower()
    hit = next((t for n, t in templates.items() if n.lower() == want), None)
    if hit is None:
        raise ValueError(f"there is no template called {name!r}")
    return hit


def block_as_written(block) -> dict:
    """A template's block back in the file form, looks and all, so an adaptation that changes only the style keeps
    the blocks."""
    written = {"type": block.type, **block.options}
    if block.name:
        written["name"] = block.name
    optional = [c.key for v, c in zip(block.values, CONTRACT.get(block.type, [])) if c.required and not v.required]
    if optional:
        written["optional"] = optional
    return written


def _plain(exc: Exception) -> str:
    """A validation error in one line: the field and what it should have been, not the library's full report."""
    text = str(exc)
    if "validation error" in text:
        lines = [line.strip() for line in text.splitlines() if line.strip() and "For further information" not in line]
        field_ = lines[1] if len(lines) > 1 else ""
        what = lines[2].split("[", 1)[0].strip() if len(lines) > 2 else ""
        return f"{field_}: {what}".strip(": ")
    return text


def _user_prompt(templates, fits: Dict[str, Fit], fired, brief: str, owner_words: str, known: str, channel: str,
                 design: str, taste: str) -> str:
    shelf = []
    for name, t in templates.items():
        f = fits[name]
        state = "can be filled" if f.ok else "cannot be filled: " + f.why_not(fired).split(": ", 1)[-1]
        shelf.append(f"- {name}: {t.description} Suits: {', '.join(t.suits) or 'anything'}. Blocks: {', '.join(b.type for b in t.blocks)}. {state}.")
    return (f"THE DESIGN BRIEF YOU WROTE\n{design.strip() or 'none'}\n\nTHE BRIEF\n{brief.strip()}\n\n"
            f"THE OWNER'S WORDS ABOUT THE DESIGN\n{owner_words.strip() or 'nothing'}\n\nWHAT IS KNOWN\n{known.strip() or 'nothing beyond the brief'}\n\n"
            f"WHAT THIS OWNER KEPT BEFORE\n{taste.strip() or 'nothing yet'}\n\nTHE SHELF ({channel})\n" + "\n".join(shelf)
            + "\n\n" + vocabulary_lines())


def vocabulary_lines() -> str:
    """The blocks with the values each needs, the looks a block may take and the style words for the whole: what a
    design may be made of, for any prompt that asks the model to compose one."""
    blocks = "\n".join(f"- {kind} ({ABOUT.get(kind, '')}): " + (", ".join(f"{v.key}{'' if v.required else ' (optional)'}" for v in vals) or "nothing") for kind, vals in CONTRACT.items())
    looks = "\n".join(f"- {k}: {' | '.join(v)}" for k, v in LOOK.items())
    style = "\n".join(f"- {name}: {' | '.join(str(a) for a in getattr(field_.annotation, '__args__', ()))}" for name, field_ in Style.model_fields.items())
    return (f"THE BLOCKS A DESIGN MAY USE (and the values each needs)\n{blocks}\n\nTHE LOOKS A BLOCK MAY TAKE\n{looks}"
            f"\n\nTHE STYLE WORDS FOR THE WHOLE\n{style}")
