"""Templates from files. A file is the Template model as JSON, with blocks written as {"type": ..., "optional":
[...], "required": [...], ...options}; the block's contract fills in the values. A file that does not validate is
refused with the reason, which is what an owner's upload will hear."""
from __future__ import annotations

import json
from pathlib import Path
from typing import Dict, List, Union

from .blocks import block
from .spec import Template


ORDINALS = ("second", "third", "fourth", "fifth", "sixth")


def template_from_dict(data: dict) -> Template:
    """A repeated block the design did not name is named here (second, third ...), so two text sections or two
    products are two sets of values instead of a refusal: the model asked for two sections and meant it."""
    blocks = []
    seen: dict = {}
    for b in data.get("blocks") or []:
        spec = {"type": b} if isinstance(b, str) else dict(b)
        type_ = spec.pop("type")
        if "name" not in spec and type_ not in ("divider", "header", "footer"):
            n = seen.get(type_, 0)
            if n:
                spec["name"] = ORDINALS[min(n - 1, len(ORDINALS) - 1)]
            seen[type_] = n + 1
        blocks.append(block(type_, **spec))
    return Template(**{**data, "blocks": blocks})


def template_from_file(path: Union[str, Path]) -> Template:
    path = Path(path)
    try:
        return template_from_dict(json.loads(path.read_text(encoding="utf-8")))
    except Exception as exc:  # noqa: BLE001 -- the file's name and the reason are the answer
        raise ValueError(f"{path.name}: {exc}") from exc


def load_templates(folder: Union[str, Path], channel: str = "") -> Dict[str, Template]:
    """Every *.template.json in a folder, by name, for one channel when given."""
    out: Dict[str, Template] = {}
    for path in sorted(Path(folder).glob("*.template.json")):
        t = template_from_file(path)
        if channel and t.channel != channel:
            continue
        out[t.name] = t
    return out
