"""The values a piece of content is made from, and whether a template fits them.

Values are gathered once per piece of content from the sources that know them (brand, journey, audience, behaviour,
identity, made). Copy values are written after the template is chosen, sized to its slots. Identity and behaviour
values may be left as tokens the sender fills per person. Missing is a fact: an optional value missing leaves its
element out; a required value missing means the template does not fit."""
from __future__ import annotations

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

from .spec import Template, Value

TOKEN = re.compile(r"\{\{slot:([a-z_.]+)\}\}")


@dataclass
class Values:
    held: Dict[str, Any] = field(default_factory=dict)            # key -> value, known when the content is written
    per_person: Dict[str, Optional[str]] = field(default_factory=dict)  # key -> fallback; the sender fills per person
    fired: Dict[str, bool] = field(default_factory=dict)          # event key -> has this account's site sent it

    def put(self, key: str, value: Any) -> None:
        if value not in (None, "", [], {}):
            self.held[key] = value

    def has(self, key: str) -> bool:
        return key in self.held or key in self.per_person

    def get(self, key: str, default: Any = None) -> Any:
        return self.held.get(key, default)


@dataclass
class Fit:
    template: Template
    missing: List[Value]        # required values nobody holds
    left_out: List[Value]       # optional values nobody holds; their elements are dropped
    too_long: List[str] = field(default_factory=list)   # copy keys over their slot size, after measure()

    @property
    def ok(self) -> bool:
        return not self.missing and not self.too_long

    def why_not(self, fired: Optional[Dict[str, bool]] = None) -> str:
        """One plain sentence naming what would make it fit."""
        parts = []
        for v in self.missing:
            if v.source == "behaviour" and v.event:
                state = "not firing yet" if not (fired or {}).get(v.event) else "firing, but not filled per person yet"
                parts.append(f"needs the {v.event} event, which is {state}")
            elif v.source == "identity":
                parts.append("needs people you know by name")
            else:
                first, _, last = v.key.rpartition(".")
                last = "link" if last == "url" else last.replace("_", " ")
                parts.append(f"needs {last if first in ('', 'cta') else first + ' ' + last}")
        for k in self.too_long:
            parts.append(f"{k.split('.')[-1].replace('_', ' ')} is longer than its space")
        return f"{self.template.name}: " + "; ".join(parts) if parts else f"{self.template.name} fits"


def fit(template: Template, values: Values) -> Fit:
    """Does this template fit these values? Copy is written after the pick, so it is never missing here. An identity
    value becomes a per-person token with its fallback. A behaviour value counts only when held for the whole
    audience or declared per person by the product."""
    missing, left_out = [], []
    for v in template.values():
        if v.source == "copy" or values.has(v.key):
            continue
        if v.source == "identity":
            values.per_person[v.key] = v.fallback
            continue
        (missing if v.required else left_out).append(v)
    return Fit(template, missing, left_out)


def measure(template: Template, copy: Dict[str, Any]) -> List[str]:
    """Copy keys whose text is longer than the slot allows."""
    over = []
    for v in template.values():
        if v.source != "copy" or v.key not in copy:
            continue
        text = copy[v.key]
        text = " ".join(" ".join(map(str, p)) if isinstance(p, (list, tuple)) else str(p) for p in text) if isinstance(text, list) else str(text)
        if (v.max_words and len(text.split()) > v.max_words) or (v.max_chars and len(text) > v.max_chars):
            over.append(v.key)
    return over


def unfilled(rendered: str) -> List[str]:
    """Slot tokens a renderer left behind. A render with any is a failed render, never sent."""
    return sorted(set(TOKEN.findall(rendered)))


def person_token(key: str, fallback: Optional[str]) -> str:
    """The token a sender fills per person, with the fallback written in: {{first_name|there}}."""
    name = key.split(".")[-1]
    return f"{{{{{name}|{fallback}}}}}" if fallback else f"{{{{{name}}}}}"
