"""The words for a chosen template: which slots the copy model writes, the prompt that asks for exactly those, and the
checks on what came back (size, and no code or figure nobody gave). Words the owner dictated are held already and are
never rewritten; the model is told them so the rest matches. The model call is a function the product passes in:
(system, user) -> {key: text}."""
from __future__ import annotations

import re
from typing import Any, Callable, Dict, List

from .spec import Template, Value
from .values import Values, measure

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

EXTRA = {"email": [Value(key="copy.subject", source="copy", max_words=9),
                   Value(key="copy.subject_named", source="copy", required=False, max_words=9),
                   Value(key="copy.preheader", source="copy", max_words=14)]}
NAME_TOKEN = "{{first_name}}"   # the one placeholder the writer may use, in copy.subject_named only; the sender fills it
CODE = re.compile(r"\b[A-Z][A-Z0-9]{3,}\b")                 # FIRST15, SAVE10: a coupon code the brief never gave
AMOUNT = re.compile(r"\d+(?:\.\d+)?\s?%|[$£€₹]\s?\d[\d,.]*")  # 15%, $299: a figure the brief never gave

SYSTEM = """You write the words for one piece of content whose design is already chosen. You are given the brief,
what is known about the brand, the audience and the facts in hand, any words the owner dictated, and the slots to
fill, each with what it is and how long it may be. Write every slot asked for and nothing else. Rules: say only
what the brief and the facts say, never invent a number, a code, a date, a place or a product; no links or web
addresses in the words, the design carries the button; no placeholders and no merge fields, except the one token
{{first_name}} in copy.subject_named, which the sender replaces with the person's first name; match the dictated
words in tone and do not repeat them; keep to each slot's length; plain language a person would say. Answer as a
JSON object whose keys are exactly the slot keys."""


class Invented(ValueError):
    """The words state a code or a figure nothing given to the writer holds."""


def slots_to_write(template: Template, values: Values) -> List[Value]:
    """The copy values this template needs that nobody holds yet, plus the channel's own (an email's subject)."""
    wanted = [v for v in template.values() if v.source == "copy"] + list(EXTRA.get(template.channel, []))
    left = [v for v in wanted if not values.has(v.key)]
    # Optional slots and the preview line ride along with the words that must be written; when every required word
    # is already held, they are not worth a call of their own.
    return [] if left and all(not v.required or v.key in ("copy.preheader", "copy.subject_named") for v in left) else left


def dictated(template: Template, values: Values) -> Dict[str, Any]:
    return {v.key: values.get(v.key) for v in template.values() if v.source == "copy" and values.has(v.key)}


def user_prompt(template: Template, slots: List[Value], values: Values, brief: str, known: str = "", voice: str = "") -> str:
    lines = []
    for v in slots:
        block = next((b.type for b in template.blocks for bv in b.values if bv.key == v.key), template.channel)
        if v.key == "facts.rows":
            shape = "a list of [label, value] pairs, only facts the brief states"
        elif v.key == "copy.body":
            shape = "a list of two or three short paragraphs, each one or two full sentences that read on from each other; never one-line fragments"
        elif v.key == "copy.subject_named":
            shape = "the subject for a person whose first name is known: the same idea as copy.subject with {{first_name}} in it once, where a name reads naturally; leave it out if a name would not"
        elif v.key == "copy.preheader":
            shape = "the preview line a mail client shows beside the subject: one sentence that adds to the subject, not a repeat of it"
        elif v.kind == "list":
            shape = "a list of short lines"
        else:
            shape = "one line"
        size = f"at most {v.max_words} words" if v.max_words else f"at most {v.max_chars} characters" if v.max_chars else "short"
        standing = "" if v.required else "; optional: leave it out unless it earns its place"
        lines.append(f"- {v.key}: the {v.key.split('.')[-1].replace('_', ' ')} of the {block}; {shape}; {size}{standing}")
    said = "\n".join(f"- {k}: {v}" for k, v in dictated(template, values).items()) or "none"
    return (f"THE BRIEF\n{brief.strip()}\n\nWHAT IS KNOWN\n{known.strip() or 'nothing beyond the brief'}\n\n"
            f"THE BRAND'S VOICE\n{voice.strip() or 'plain and warm'}\n\nWORDS THE OWNER DICTATED (already placed, do not rewrite)\n{said}\n\n"
            f"THE SLOTS TO WRITE\n" + "\n".join(lines))


def invented(answer: Dict[str, Any], given: str) -> List[str]:
    """Codes and amounts in the answer that appear nowhere in what the writer was given."""
    text = " ".join(_flat(v) for v in answer.values())
    have = given.upper().replace(" ", "")
    return sorted({m for m in CODE.findall(text) + AMOUNT.findall(text) if m.upper().replace(" ", "") not in have})


def write(template: Template, values: Values, brief: str, ask: Ask, known: str = "", voice: str = "") -> Dict[str, Any]:
    """Fills the template's copy slots into `values`. A slot over its size, or words stating a code or a figure
    nobody gave, are asked for again once with the reason; words still inventing are refused (Invented). Returns
    {key: text} of what was written."""
    slots = slots_to_write(template, values)
    if not slots:
        return {}
    prompt = user_prompt(template, slots, values, brief, known, voice)
    given = " ".join([brief, known, _flat(list(dictated(template, values).values())),
                      " ".join(str(values.get(k) or "") for k in ("offer.code", "offer.said", "cart.total", "product.price"))])
    answer = _only(slots, ask(SYSTEM, prompt) or {})
    over = measure(template, answer) + [k for k in ("copy.subject",) if k in answer and len(str(answer[k]).split()) > 9]
    made_up = invented(answer, given)
    if over or made_up:
        again = prompt
        if over:
            again += "\n\nThese came back too long; write only these again, within their size:\n" + "\n".join(f"- {k}: {_size(slots, k)}" for k in over)
        if made_up:
            again += ("\n\nThese were stated but nothing you were given holds them, so they must not appear: " + ", ".join(made_up)
                      + ". Write every slot again without them. Say there is a code or a discount only when one was given.")
        retry = _only(slots, ask(SYSTEM, again) or {})
        answer.update({k: v for k, v in retry.items() if made_up or k in over})
        still = invented(answer, given)
        if still:
            raise Invented(f"the words state {', '.join(still)}, which the brief and the journey do not give")
    for key, text in answer.items():
        values.put(key, text)
    return answer


def _only(slots: List[Value], answer: Dict[str, Any]) -> Dict[str, Any]:
    keys = {v.key for v in slots}
    return {k: v for k, v in answer.items() if k in keys and v not in (None, "", [], {})}


def _size(slots: List[Value], key: str) -> str:
    v = next((s for s in slots if s.key == key), None)
    return f"at most {v.max_words} words" if v and v.max_words else f"at most {v.max_chars} characters" if v and v.max_chars else "short"


def _flat(v: Any) -> str:
    if isinstance(v, (list, tuple)):
        return " ".join(_flat(x) for x in v)
    return str(v or "")
