"""The look at what was made: the model sees the rendered piece as a picture, judges it against its own design
brief, and names at most a few fixes: a look on a block, a style word on the whole. Code applies them to the
template and the product renders once more. The model call, with the picture, is the product's."""
from __future__ import annotations

from typing import Any, Callable, Dict, List

from .blocks import LOOK, block
from .load import template_from_dict
from .spec import Style, Template

Ask = Callable[[str, str], Dict[str, Any]]

SYSTEM = """You are looking at a rendered piece of content you art-directed, beside the design brief you wrote for it.
Judge it as a designer would: does the eye land where the brief said, is the hierarchy right, is it too dense or too
thin, is the picture doing its job, does the accent sit where it should, does it look like this brand. Then answer
with the smallest set of fixes that makes it right, or none. A fix changes the look of one block (by its number in
the list given) or a style word for the whole. Never change words or add blocks. Answer as JSON:
{"verdict": "keep|fix", "note": "one sentence for the owner", "fixes": [{"block": <number>, "look": {<look words>}},
{"style": {<style words>}}]}."""


def user_prompt(template: Template, design_lines: str) -> str:
    blocks = "\n".join(f"{i}. {b.type}" + (f" ({b.name})" if b.name else "") + (f" looks: {b.options}" if b.options else "")
                       for i, b in enumerate(template.blocks))
    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 DESIGN BRIEF YOU WROTE\n{design_lines}\n\nTHE BLOCKS, IN ORDER\n{blocks}\n\nTHE LOOK WORDS A BLOCK MAY TAKE\n{looks}\n\n"
            f"THE STYLE WORDS FOR THE WHOLE\n{style}\n\nThe picture of the piece as rendered is attached.")


def apply_fixes(template: Template, fixes: List[dict]) -> Template:
    """The template with the judge's fixes on it. A fix naming a block that is not there, or a look word that does not
    exist, is skipped: the judge may only move within the vocabulary."""
    data = template.model_dump()
    written = []
    for b in template.blocks:
        w = {"type": b.type, **b.options}
        if b.name:
            w["name"] = b.name
        optional = [v.key for v in b.values if not v.required and _contract_required(b.type, v.key)]
        if optional:
            w["optional"] = optional
        written.append(w)
    for fix in fixes or []:
        if not isinstance(fix, dict):
            continue
        if "style" in fix and isinstance(fix["style"], dict):
            data["style"] = {**data["style"], **{k: v for k, v in fix["style"].items() if k in Style.model_fields}}
        if "block" in fix and isinstance(fix.get("look"), dict):
            try:
                at = int(fix["block"])
            except (TypeError, ValueError):
                continue
            if 0 <= at < len(written):
                for k, v in fix["look"].items():
                    if k in LOOK and str(v) in LOOK[k]:
                        written[at][k] = str(v)
    data["blocks"] = written
    return template_from_dict(data)


def _contract_required(type_: str, key: str) -> bool:
    from .blocks import CONTRACT
    base = key.split(".", 1)[-1]
    return any(v.required and v.key.split(".", 1)[-1] == base for v in CONTRACT.get(type_, []))
