#!/usr/bin/env python3
"""Validate an OKF bundle. Usage: okf-check <okf-dir>

Errors (exit 1): missing type, missing warrant, duplicate answer,
unresolvable cite, unprefixed register cite in prose, discharged roadmap
phase keeping a verify step, malformed `okf:derived` fence, page
unreachable from index.md, page over its line cap, register index line
disagreeing with its decision file, moored ferry with a malformed
`sealed:` pin or a surviving directory, a directory holding `.md` files
with no `index.md` (an open ferry topic directory may carry `MAP.md`
instead), an `index.md` not directly linking every `.md` file physically
beside it. Warnings (exit 0): page with no cites, blueprint locked
without a `sounded:` stamp.

Pin *shape* only — whether the change id still resolves needs the repo in
hand, which is write-okf refresh's job, not a validator that must exit 0
on an OKF tree copied outside its jj repo.
"""
import re
import sys
from pathlib import Path

CAP = 110
WIDE_CAP = 250  # Roadmap, Glossary, Guide, and blueprints — worked against, not read cold
LINE_SUFFIX = re.compile(r"\d+(-\d+)?")


def frontmatter(text):
    """Parse the leading --- block. Returns {} when absent.

    Handles scalars, inline lists (`answers: [a, b]`) and block lists
    (`answers:` followed by indented `- ` items).
    """
    if not text.startswith("---\n"):
        return {}
    end = text.find("\n---", 3)
    if end == -1:
        return {}
    fields, key = {}, None
    for line in text[4:end].splitlines():
        item = re.match(r"\s+-\s+(.*)", line)
        if item and key:
            fields[key].append(unquote(item.group(1)))
            continue
        pair = re.match(r"([A-Za-z_-]+):\s*(.*)", line)
        if not pair:
            continue
        key, raw = pair.group(1), pair.group(2).strip()
        if raw.startswith("[") and raw.endswith("]"):
            fields[key] = [unquote(v) for v in raw[1:-1].split(",") if v.strip()]
        elif raw:
            fields[key] = unquote(raw)
            key = None
        else:
            fields[key] = []
    return fields


def unquote(value):
    value = value.strip()
    if len(value) > 1 and value[0] == value[-1] and value[0] in "\"'":
        return value[1:-1]
    return value


def links(text):
    """Markdown link targets, minus anchors and external URLs."""
    out = []
    for target in re.findall(r"\]\(([^)]+)\)", text):
        target = target.split("#")[0].strip()
        if target and "://" not in target:
            out.append(target)
    return out


def reachable(okf, pages):
    """Pages reachable from index.md, transitively through index pages.

    A ferry's decision files are covered by their MAP.md, which is the
    single home for them by layout contract.
    """
    seen, frontier = set(), [okf / "index.md"]
    while frontier:
        page = frontier.pop()
        if page in seen or not page.exists():
            continue
        seen.add(page)
        if page.name not in ("index.md", "MAP.md"):
            continue
        for target in links(page.read_text()):
            frontier.append((page.parent / target).resolve())
    for page in pages:
        parent_map = page.parent / "MAP.md"
        if parent_map in seen:
            seen.add(page)
    return seen


def cite_resolves(cite, page, okf):
    """`path` and `path:line` need the path; `path:symbol` needs both.

    The symbol is matched as a literal substring — no language awareness,
    no tags file. A `:suffix` that is a line number or a line range is a
    reading aid, never validated: a check that cannot fail is not a check.
    """
    path, _, symbol = cite.split("#")[0].partition(":")
    path, symbol = path.strip(), symbol.strip()
    if not path:
        return False
    if LINE_SUFFIX.fullmatch(symbol):
        symbol = ""
    for root in (page.parent, okf, okf.parent):
        target = root / path
        if not target.exists():
            continue
        if not symbol:
            return True
        if target.is_file() and symbol in target.read_text():
            return True
    return False


def register_numbers(okf):
    """Three-digit numbers naming a live file in either register.

    Filenames carry their register's prefix (R-024's rename) — B- for
    blueprints, R- for decisions — so the number sits two characters in.
    """
    return {p.name[2:5] for prefix, register in (("B", "blueprints"), ("R", "decisions"))
            for p in (okf / register).glob(f"{prefix}-[0-9][0-9][0-9]-*.md")}


def prose_cites(text, numbers):
    """Bare register numbers standing in a page's prose.

    Blueprints and the why-register number independently, so a bare `019`
    names two unrelated pages and a reader resolves it by guessing. The
    exclusions are the rule's hard half and all mechanical: frontmatter,
    fenced blocks, code spans, whole markdown links (text and target
    both — the path already says which register), and the page's own H1.
    A number touching `/`, `-`, `.` or a word character is part of a path,
    a date or a `superseded-by-NNN`, never a cite.
    """
    body = text.partition("\n---")[2] if text.startswith("---\n") else text
    body = re.sub(r"^```.*?^```", " ", body, flags=re.M | re.S)
    body = re.sub(r"`[^`]*`", " ", body)
    body = re.sub(r"\[[^\]]*\]\([^)]*\)", " ", body)
    body = re.sub(r"^#.*$", " ", body, flags=re.M)
    found = re.findall(r"(?<![\w/.-])\d{3}(?![\w/.-])", body)
    return sorted({n for n in found if n in numbers})


def fence_error(text):
    """Shape of the derived zone: at most one region, begin before end.

    A fence owns its whole line, so a page that merely *mentions* the
    markers in prose or in a command is not fenced.
    """
    marks = re.findall(r"^<!-- okf:derived (begin|end) -->$", text, re.M)
    if marks and marks != ["begin", "end"]:
        return f"malformed okf:derived fence: {' '.join(marks)}"
    return None


def pin(text):
    """Fields of `sealed:`, the one nested block the frontmatter carries."""
    head = text.partition("\n---")[0] if text.startswith("---\n") else ""
    block = re.search(r"^sealed:\n((?:[ \t]+.*\n?)+)", head, re.M)
    return dict(re.findall(r"([a-z]+):\s*(\S+)", block.group(1))) if block else {}


def tally(text):
    """Fields of `tally:`, muster's verdict block — parsed like `pin`.

    The generic frontmatter parser flattens a nested block to an empty
    list, so a dedicated grab is the only way to see it.
    """
    head = text.partition("\n---")[0] if text.startswith("---\n") else ""
    block = re.search(r"^tally:\n((?:[ \t]+.*\n?)+)", head, re.M)
    return dict(re.findall(r"([a-z]+):\s*(\S+)", block.group(1))) if block else {}


def check_roadmap(text, rel, errors):
    """A discharged phase keeps no verify step — R-020's prune, mechanised.

    A phase entry runs from its `^\\d+\\. ` line to the next such line or the
    next `## ` heading, so a wrapped `**Verify:**` still belongs to the phase
    above it. The tick says the step ran; where it ran is jj history.
    """
    entry = []

    def close():
        block = "\n".join(entry)
        if entry and "✅" in block and "**Verify:**" in block:
            errors.append(f"{rel}: discharged phase keeps a verify step: {entry[0][:40]}")

    for line in text.splitlines():
        phase = re.match(r"\d+\. ", line)
        if phase or line.startswith("## "):
            close()
            entry = [line] if phase else []
        elif entry:
            entry.append(line)
    close()


def check_dir_index(okf, errors):
    """Every OKF directory holding `.md` files carries an entry point.

    Directly under `ferries/`, an open ferry topic directory is fronted
    by `MAP.md` instead — R-015's directory-means-open shape; a moored
    ferry is a single file, never a directory, so it never reaches here.
    """
    dirs = {p.parent for p in okf.rglob("*.md")}
    for d in sorted(dirs):
        entry = "MAP.md" if d.parent == okf / "ferries" else "index.md"
        if not (d / entry).exists():
            rel = d.relative_to(okf.parent)
            errors.append(f"{rel}: directory holds .md files with no {entry}")


def check_index_completeness(okf, errors):
    """`index.md` directly links every `.md` file beside it.

    Independent of `reachable()`'s transitive, whole-tree check — a page
    linked only from a grandparent index still fails this one. `MAP.md`
    carries its own D-n table shape and is exempt.
    """
    for idx in okf.rglob("index.md"):
        d = idx.parent
        siblings = {p.resolve() for p in d.glob("*.md") if p.name != "index.md"}
        linked = {(d / t).resolve() for t in links(idx.read_text())}
        missing = siblings - linked
        if missing:
            rel = idx.relative_to(okf.parent)
            names = ", ".join(sorted(p.name for p in missing))
            errors.append(f"{rel}: index.md missing {names}")


def check_ferries(okf, errors):
    """A page directly under ferries/ is a moored ferry: pinned, collapsed."""
    ferries = okf / "ferries"
    if not ferries.is_dir():
        return
    for page in sorted(ferries.glob("*.md")):
        if page.name == "index.md":
            continue
        rel = page.relative_to(okf.parent)
        if (ferries / page.stem).is_dir():
            errors.append(f"{rel}: coexists with ferries/{page.stem}/ — open or moored, never both")
        fields = pin(page.read_text())
        missing = [f for f in ("change", "commit", "date") if f not in fields]
        if missing:
            errors.append(f"{rel}: sealed: missing {', '.join(missing)}")
            continue
        if not re.fullmatch(r"[0-9a-f]{8,64}", fields["commit"]):
            errors.append(f"{rel}: sealed: commit is not a hex hash: {fields['commit']}")
        if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", fields["date"]):
            errors.append(f"{rel}: sealed: date is not ISO 8601: {fields['date']}")


def check_register(okf, warrants, errors):
    """Register index lines must quote their decision's own question."""
    index = okf / "decisions" / "index.md"
    if not index.exists():
        return
    for line in index.read_text().splitlines():
        if not line.startswith("- "):
            continue
        target = links(line)
        fields = line.split(" — ")
        if not target or len(fields) < 2:
            errors.append(f"{index}: malformed register line: {line}")
            continue
        page = (index.parent / target[0]).resolve()
        answers = warrants.get(page, {}).get("answers") or []
        if not answers:
            errors.append(f"{index}: line points at a page with no answers: {target[0]}")
        elif fields[1].strip() != answers[0]:
            errors.append(
                f"{index}: line question disagrees with {target[0]}: "
                f"{fields[1].strip()!r} vs {answers[0]!r}"
            )


def main(argv):
    if len(argv) != 2:
        print("usage: okf-check <okf-dir>", file=sys.stderr)
        return 2
    okf = Path(argv[1]).resolve()
    if not okf.is_dir():
        print(f"not a directory: {okf}", file=sys.stderr)
        return 2

    pages = sorted(p.resolve() for p in okf.rglob("*.md"))
    index = okf / "index.md"
    errors, warnings, warrants, answered = [], [], {}, {}
    seen = reachable(okf, pages)
    numbers = register_numbers(okf)

    for page in pages:
        text = page.read_text()
        fields = frontmatter(text)
        warrants[page] = fields
        rel = page.relative_to(okf.parent)

        if page not in seen:
            errors.append(f"{rel}: not reachable from index.md")
        fence = fence_error(text)
        if fence:
            errors.append(f"{rel}: {fence}")
        if page == index:
            continue
        if not fields.get("type"):
            errors.append(f"{rel}: missing type:")
        # Every page kind has a growth path at cap+1, so the cap is an
        # error: a legal move always exists. See split-page.md. Wide
        # pages are selected by declared type, not path, so ROADMAP.md
        # and CONTEXT.md get the wider cap wherever they live.
        wide = ("blueprints" in rel.parts
                or fields.get("type") in ("Roadmap", "Glossary", "Guide"))
        cap = WIDE_CAP if wide else CAP
        if len(text.splitlines()) > cap:
            errors.append(f"{rel}: over the {cap}-line cap")

        # Sounding is a precondition of lock. Only at `locked`: `draft` is
        # not-yet-sounded, and `implemented` would retro-flag 002-006.
        if ("blueprints" in rel.parts and fields.get("status") == "locked"
                and not fields.get("sounded")):
            warnings.append(f"{rel}: locked without sounded:")

        # muster is opt-in: a blueprint carrying `muster: true` may not
        # reach `implemented` without its `tally:`, and never on a known
        # miss — the human verdict the gate exists to force. Blueprints
        # without the field are untouched.
        if ("blueprints" in rel.parts
                and str(fields.get("muster", "")).lower() == "true"
                and fields.get("status") == "implemented"):
            verdict = tally(text)
            if not verdict:
                errors.append(f"{rel}: muster: true, implemented without tally:")
            elif verdict.get("matches") == "no":
                errors.append(f"{rel}: muster: true, implemented with tally: matches: no")

        # A cite is a working pointer, so every page carries the rule at
        # every status — a blueprint's `cites:` are not frozen by lock.
        cites = fields.get("cites") or []
        for cite in cites:
            if not cite_resolves(cite, page, okf):
                errors.append(f"{rel}: unresolvable cite: {cite}")

        if fields.get("type") == "Roadmap":
            check_roadmap(text, rel, errors)

        # The warrant contract covers durable synthesis pages; blueprints
        # and ferries carry their own frontmatter contracts.
        if {"blueprints", "ferries"} & set(rel.parts) or page.name == "index.md":
            continue
        if not fields.get("purpose"):
            errors.append(f"{rel}: missing purpose:")
        if not fields.get("answers"):
            errors.append(f"{rel}: missing answers:")
        for answer in fields.get("answers") or []:
            if answer in answered:
                errors.append(f"{rel}: answers a question {answered[answer]} owns: {answer}")
            else:
                answered[answer] = rel
        if not cites:
            warnings.append(f"{rel}: no cites:")

        # A prose cite carries its register's prefix. Learnings pages are
        # exempt — append-only by their own header, so their bare numbers
        # stand as written. Typing the exemption is what survives the
        # LEARNINGS.md → learnings/<theme>.md split.
        if fields.get("type") != "Learnings":
            for number in prose_cites(text, numbers):
                errors.append(f"{rel}: unprefixed register cite: {number}")

    check_ferries(okf, errors)
    check_register(okf, warrants, errors)
    check_dir_index(okf, errors)
    check_index_completeness(okf, errors)

    for line in warnings:
        print(f"WARN  {line}")
    for line in errors:
        print(f"ERROR {line}")
    print(f"{len(errors)} error(s), {len(warnings)} warning(s)")
    return 1 if errors else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))
