"""The authoring standard's exemplar specs must stay valid.

notes/authoring-workflows.md is the instruction set handed to AI builders; a
drifted example would teach every future builder a broken shape. Extract its
json blocks and run them through the real validator.
"""
import json
import re
from pathlib import Path

from app.schemas import validate_spec

DOC = Path(__file__).resolve().parents[2] / "notes" / "authoring-workflows.md"


def test_authoring_doc_examples_validate():
    """Blocks are classified by SHAPE, not position — the doc grows new
    snippets over time and indexing by position silently retargets them."""
    blocks = [json.loads(b) for b in
              re.findall(r"```json\n(.*?)```", DOC.read_text(), re.S)]
    specs = [b for b in blocks if "steps" in b]
    sets_ = [b for b in blocks if "items" in b]
    fragments = [b for b in blocks if "steps" not in b and "items" not in b]

    assert specs, "the doc must keep at least one full workflow example"
    for spec in specs:
        validate_spec(spec)

    assert sets_, "the doc must keep its template-set example"
    for st in sets_:
        assert st["items"] and all("template_key" in i for i in st["items"])

    # Step fragments (e.g. the choices example) aren't whole specs, so wrap
    # each in a minimal workflow and check it really is valid in context.
    for frag in fragments:
        validate_spec({"key": "doc_frag", "title": "Doc fragment",
                       "start": frag["id"], "steps": [
                           frag,
                           {"id": "team_ack", "owner": "team",
                            "primary": {"label": "Noted", "to": "$done"}}]})
