"""
lean_config.py - how plan.md says a source binds, shared with the sibling skills' copies.

validate_plan.py reads whether plan.md's `## Sources` marks a source binding from here. The
screen and proof helpers below serve the sibling skills that ship this same file; this skill has
no checks.md since 3.0.0 and does not call them.

Every function takes lines already stripped of fenced blocks.
"""

import re

RUN_RE = re.compile(r"^\**\s*Run\s+([\w-]+)\s*\**\s*:\s*(.+)$", re.IGNORECASE)
RUN_PROOF_RE = re.compile(r"^run\s+([\w-]+)\s*\|\s*(.*)$", re.IGNORECASE)
BINDING_RE = re.compile(r"(?<![-\w])binding\b", re.IGNORECASE)
NOT_BINDING_RE = re.compile(r"\b(non|not)[- ]binding\b", re.IGNORECASE)
CAPTURE_RE = re.compile(r"`([^`\s]+\.(?:png|jpe?g|webp|gif))`", re.IGNORECASE)
SCREEN_CRITERION_RE = re.compile(r"\bSHALL\s+(?:NOT\s+)?(?:show|display|render|hide)\b", re.IGNORECASE)
PROOF_RE = re.compile(r"^\**\s*Proof\s*\**\s*:\s*`?browser\b", re.IGNORECASE)
CRITERION_RE = re.compile(r"^\s*\d+\.\s+(.*)$")
APPROVED_RE = re.compile(
    r"^\**\s*Approved\s*\**\s*:\s*\**\s*\d{4}-\d{2}-\d{2}\b.*\buser\s*:\s*[\"“][^\"”]*\S[^\"”]*[\"”]",
    re.IGNORECASE)


def plan_approved(plan_lines):
    """True when plan.md carries `**Approved**: <date> - user: "<their words>"`. The approval is the
    user's, so it carries their words; the chat that held it does not survive a compaction."""
    return any(APPROVED_RE.match(s.strip()) for s in plan_lines)


def read_runs(lines):
    """{name: command} for every `Run <name>: <command>` line."""
    runs = {}
    for ln in lines:
        m = RUN_RE.match(ln.strip())
        if m:
            runs[m.group(1)] = m.group(2).strip().strip("`").strip()
    return runs


def _section(lines, name):
    """The lines under a `#`/`##` heading named `name`, up to the next `#`/`##` heading."""
    out, inside = [], False
    for ln in lines:
        s = ln.strip()
        if re.match(r"^#{1,2}\s+\S", s):
            inside = re.match(r"^#{1,2}\s+" + re.escape(name) + r"\b", s, re.IGNORECASE) is not None
            continue
        if inside:
            out.append(s)
    return out


def plan_criteria(plan_lines):
    """The text of every numbered criterion under `## Criteria`."""
    out = []
    for s in _section(plan_lines, "Criteria"):
        m = CRITERION_RE.match(s)
        if m:
            out.append(m.group(1))
    return out


def plan_has_screen(plan_lines, checks_lines=()):
    """True when the feature puts a screen in front of a user.

    A criterion that cites a capture or says the system SHALL show, display, render or hide
    something is a screen criterion; so is a `browser` proof in checks.md.
    """
    for text in plan_criteria(plan_lines):
        if CAPTURE_RE.search(text) or SCREEN_CRITERION_RE.search(text):
            return True
    return any(PROOF_RE.match(s.strip()) for s in checks_lines)


def plan_owes_pictures(plan_lines, checks_lines=()):
    """True when the feature owes running pictures: a criterion cites a capture, or a check is
    proven in the browser. A screen state no capture draws is proven by a test or a walk."""
    if any(CAPTURE_RE.search(text) for text in plan_criteria(plan_lines)):
        return True
    return any(PROOF_RE.match(s.strip()) for s in checks_lines)


def plan_marks_binding(plan_lines):
    """True when plan.md's `## Sources` marks a source binding (the binding-source comparison runs)."""
    return any(BINDING_RE.search(s) and not NOT_BINDING_RE.search(s) for s in _section(plan_lines, "Sources"))
