#!/usr/bin/env python3
"""wiki - navigate, search and validate an Open Knowledge Format bundle.

Zero dependencies: Python 3 standard library only. Uses PyYAML automatically if
it happens to be installed, otherwise falls back to a parser for the YAML subset
OKF actually uses.

Operates on the bundle relative to this script's own location, so it works from
any working directory.
"""
from __future__ import annotations

import argparse
import datetime as dt
import os
import re
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
# WIKI_ROOT lets the test suite point the tool at fixture bundles. Unset, the tool
# operates on the bundle beside it, so it works from any working directory.
WIKI = Path(os.environ["WIKI_ROOT"]).resolve() if os.environ.get("WIKI_ROOT") else ROOT / "wiki"
RESERVED = {"index.md", "log.md"}

# Size guard thresholds. Past these, the index no longer reliably fits in context
# and progressive disclosure starts to degrade (Karpathy: "~100 sources, ~hundreds
# of pages").
MAX_PAGES = 300
MAX_SOURCES = 100
MAX_INDEX_BYTES = 8000

ISO_UTC = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$")
ISO_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
ACTOR = re.compile(r"^(?:human:[\w.-]+|process:[\w.-]+|[\w.-]+/[\w.\-]+)$")
TAG_OK = re.compile(r"^[a-z][a-z0-9]*(?:[-/][a-z0-9]+)*$")
STATUSES = {"draft", "stable", "deprecated"}
TIMESTAMP_KEYS = {"at", "last_modified", "stale_after", "from", "to"}


# --------------------------------------------------------------------------- #
# Frontmatter
# --------------------------------------------------------------------------- #
def split_frontmatter(text: str):
    """Return (state, raw_yaml, body). state: 'none' | 'ok' | 'unterminated'."""
    if not text.startswith("---"):
        return "none", "", text
    lines = text.split("\n")
    if lines[0].strip() != "---":
        return "none", "", text
    for i in range(1, len(lines)):
        if lines[i].strip() in ("---", "..."):
            return "ok", "\n".join(lines[1:i]), "\n".join(lines[i + 1:])
    return "unterminated", "", text


def _scalar(v: str):
    v = v.strip()
    if not v:
        return None
    if len(v) >= 2 and v[0] == v[-1] and v[0] in "\"'":
        return v[1:-1].replace("''", "'")
    if v.startswith("[") and v.endswith("]"):
        return [_scalar(x) for x in _split_flow(v[1:-1])] if v[1:-1].strip() else []
    if v.startswith("{") and v.endswith("}"):
        out = {}
        for part in _split_flow(v[1:-1]):
            if ":" in part:
                k, _, rest = part.partition(":")
                out[k.strip()] = _scalar(rest)
        return out
    if v in ("true", "True"):
        return True
    if v in ("false", "False"):
        return False
    return v


def _split_flow(s: str):
    """Split a flow collection body on commas that are not nested or quoted."""
    parts, depth, quote, cur = [], 0, None, ""
    for ch in s:
        if quote:
            cur += ch
            if ch == quote:
                quote = None
            continue
        if ch in "\"'":
            quote, cur = ch, cur + ch
            continue
        if ch in "[{":
            depth += 1
        elif ch in "]}":
            depth -= 1
        if ch == "," and depth == 0:
            parts.append(cur)
            cur = ""
        else:
            cur += ch
    if cur.strip():
        parts.append(cur)
    return [p.strip() for p in parts]


def _fallback_parse(raw: str):
    """Parse the YAML subset OKF uses: scalars, flow collections, block lists,
    lists of mappings, and one level of nested block mappings."""
    lines = [ln for ln in raw.split("\n") if ln.strip() and not ln.lstrip().startswith("#")]
    data, i = {}, 0

    def indent(ln):
        return len(ln) - len(ln.lstrip())

    while i < len(lines):
        ln = lines[i]
        if indent(ln) != 0 or ":" not in ln:
            i += 1
            continue
        key, _, rest = ln.partition(":")
        key, rest = key.strip(), rest.strip()
        if rest:
            data[key] = _scalar(rest)
            i += 1
            continue
        # Block value: gather the indented region.
        block, i = [], i + 1
        while i < len(lines) and indent(lines[i]) > 0:
            block.append(lines[i])
            i += 1
        if not block:
            data[key] = None
            continue
        if block[0].lstrip().startswith("- "):
            items, cur = [], None
            base = indent(block[0])
            for b in block:
                s = b.lstrip()
                if indent(b) == base and s.startswith("- "):
                    if cur is not None:
                        items.append(cur)
                    inner = s[2:].strip()
                    if inner.startswith("{") or ":" not in inner:
                        cur = _scalar(inner)
                    else:
                        k, _, v = inner.partition(":")
                        cur = {k.strip(): _scalar(v)}
                elif isinstance(cur, dict) and ":" in s:
                    k, _, v = s.partition(":")
                    cur[k.strip()] = _scalar(v)
            if cur is not None:
                items.append(cur)
            data[key] = items
        else:
            sub = {}
            for b in block:
                s = b.strip()
                if ":" in s:
                    k, _, v = s.partition(":")
                    sub[k.strip()] = _scalar(v)
            data[key] = sub
    return data


try:  # optional; the fallback is fully sufficient for OKF
    import yaml as _yaml

    def parse_yaml(raw: str):
        try:
            out = _yaml.safe_load(raw)
            return out if isinstance(out, dict) else ({} if out is None else {"__scalar__": out})
        except Exception:
            return None
except Exception:  # pragma: no cover
    def parse_yaml(raw: str):
        try:
            return _fallback_parse(raw)
        except Exception:
            return None


# --------------------------------------------------------------------------- #
# Bundle model
# --------------------------------------------------------------------------- #
class Page:
    __slots__ = ("path", "rel", "cid", "state", "meta", "body", "text", "fm_start")

    def __init__(self, path: Path):
        self.path = path
        self.rel = path.relative_to(WIKI).as_posix()
        self.cid = self.rel[:-3]
        self.text = path.read_text(encoding="utf-8", errors="replace")
        self.state, raw, self.body = split_frontmatter(self.text)
        self.meta = parse_yaml(raw) if self.state == "ok" else None
        self.fm_start = 2  # first frontmatter key sits on line 2

    @property
    def reserved(self):
        return self.path.name in RESERVED

    def get(self, key, default=None):
        return (self.meta or {}).get(key, default)


def load_pages():
    if not WIKI.is_dir():
        sys.exit(f"wiki: no bundle at {WIKI}")
    return [Page(p) for p in sorted(WIKI.rglob("*.md"))]


FENCE = re.compile(r"^\s*(```|~~~)")


def strip_code(body: str) -> str:
    """Blank out fenced code blocks so link scans do not read code as prose."""
    out, fence = [], None
    for ln in body.split("\n"):
        m = FENCE.match(ln)
        if fence is None and m:
            fence, ln = m.group(1), ""
        elif fence and ln.strip().startswith(fence):
            fence, ln = None, ""
        elif fence:
            ln = ""
        out.append(ln)
    return "\n".join(out)


MD_LINK = re.compile(r"(!?)\[([^\]]*)\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
WIKILINK = re.compile(r"(?<!\\)\[\[([^\]]+)\]\]")
FOOTNOTE_REF = re.compile(r"(?<!\])\[\^([^\]]+)\](?!:)")
FOOTNOTE_DEF = re.compile(r"^\[\^([^\]]+)\]:", re.M)


# --------------------------------------------------------------------------- #
# Commands
# --------------------------------------------------------------------------- #
def cmd_index(args):
    target = (WIKI / args.path).resolve() if args.path else WIKI
    if not str(target).startswith(str(WIKI)):
        sys.exit("wiki: path escapes the bundle")
    if target.is_file():
        target = target.parent
    idx = target / "index.md"
    if idx.is_file():
        print(idx.read_text(encoding="utf-8").rstrip())
        return 0
    # OKF §8: a consumer MAY synthesize an index when none is present.
    print(f"# {target.relative_to(WIKI).as_posix() or 'index'} (synthesized)\n")
    for child in sorted(target.iterdir()):
        if child.is_dir() and any(child.rglob("*.md")):
            print(f"* [{child.name}]({child.name}/)")
    for child in sorted(target.glob("*.md")):
        if child.name in RESERVED:
            continue
        p = Page(child)
        desc = p.get("description") or ""
        title = p.get("title") or child.stem
        print(f"* [{title}]({child.name})" + (f" - {desc}" if desc else ""))
    return 0


def cmd_read(args):
    cid = args.concept_id
    if not cid.endswith(".md"):
        cid += ".md"
    target = (WIKI / cid).resolve()
    if not str(target).startswith(str(WIKI)) or not target.is_file():
        sys.exit(f"wiki: no such concept: {args.concept_id}")
    print(target.read_text(encoding="utf-8").rstrip())
    return 0


def cmd_search(args):
    needles = [n.lower() for n in args.query]
    hits = []
    for p in load_pages():
        if p.reserved:
            continue
        state, raw, body = split_frontmatter(p.text)
        strong, weak = raw.lower(), body.lower()
        # Frontmatter matches count per occurrence and weigh 3x; body matches
        # count once per page. Cheap, predictable, and good enough at wiki scale.
        score = sum(3 * strong.count(n) + (1 if n in weak else 0) for n in needles)
        if score:
            hits.append((score, p))
    hits.sort(key=lambda h: (-h[0], h[1].cid))
    for score, p in hits[: args.limit]:
        desc = p.get("description") or ""
        print(f"{score:>4}  {p.cid}" + (f"  - {desc}" if desc else ""))
    if not hits:
        print("no matches", file=sys.stderr)
        return 1
    return 0


def cmd_list(args):
    rows = []
    for p in load_pages():
        if p.reserved or not p.meta:
            continue
        if args.type and str(p.get("type", "")).lower() != args.type.lower():
            continue
        if args.status and str(p.get("status", "stable")).lower() != args.status.lower():
            continue
        tags = p.get("tags") or []
        if args.tag and args.tag not in (tags if isinstance(tags, list) else [tags]):
            continue
        rows.append((str(p.get("type", "?")), p.cid, p.get("description") or ""))
    width = max((len(r[0]) for r in rows), default=0)
    for t, cid, desc in sorted(rows):
        print(f"{t:<{width}}  {cid}" + (f"  - {desc}" if desc else ""))
    return 0


def cmd_stats(args):
    pages = [p for p in load_pages() if not p.reserved]
    types, tags, unverified, stale, drafts = {}, set(), 0, 0, 0
    src_ids = set()
    now = dt.datetime.now(dt.timezone.utc)
    for p in pages:
        types[str(p.get("type", "?"))] = types.get(str(p.get("type", "?")), 0) + 1
        for t in p.get("tags") or []:
            tags.add(t)
        if not p.get("verified"):
            unverified += 1
        if str(p.get("status", "stable")) == "draft":
            drafts += 1
        sa = p.get("stale_after")
        if isinstance(sa, str) and ISO_UTC.match(sa):
            if dt.datetime.fromisoformat(sa.replace("Z", "+00:00")) <= now:
                stale += 1
        for s in p.get("sources") or []:
            if isinstance(s, dict) and s.get("resource"):
                src_ids.add(str(s["resource"]))
    print(f"pages         {len(pages)}")
    print(f"distinct sources {len(src_ids)}")
    print(f"tags          {len(tags)}")
    print(f"unverified    {unverified}")
    print(f"drafts        {drafts}")
    print(f"stale         {stale}")
    print("\ntypes:")
    for t, n in sorted(types.items(), key=lambda kv: -kv[1]):
        print(f"  {n:>4}  {t}")

    root_idx = WIKI / "index.md"
    idx_bytes = root_idx.stat().st_size if root_idx.is_file() else 0
    warn = []
    if len(pages) > MAX_PAGES:
        warn.append(f"{len(pages)} pages (> {MAX_PAGES})")
    if len(src_ids) > MAX_SOURCES:
        warn.append(f"{len(src_ids)} sources (> {MAX_SOURCES})")
    if idx_bytes > MAX_INDEX_BYTES:
        warn.append(f"root index is {idx_bytes} bytes (> {MAX_INDEX_BYTES})")
    if warn:
        print("\nsize guard:")
        for w in warn:
            print(f"  ! {w}")
        print("  This wiki is outgrowing pure progressive disclosure. Consider splitting")
        print("  it into sub-bundles by topic, or lean on `wiki search` for retrieval.")
    return 0


# --------------------------------------------------------------------------- #
# lint
# --------------------------------------------------------------------------- #
class Report:
    def __init__(self):
        self.items = []

    def add(self, level, rule, path, line, msg):
        self.items.append((level, rule, path, line, msg))

    fail = lambda self, *a: self.add("FAIL", *a)
    warn = lambda self, *a: self.add("WARN", *a)

    def render(self, quiet=False):
        order = {"FAIL": 0, "WARN": 1}
        self.items.sort(key=lambda i: (order[i[0]], i[2], i[3]))
        fails = sum(1 for i in self.items if i[0] == "FAIL")
        for level, rule, path, line, msg in self.items:
            if quiet and level != "FAIL":
                continue
            loc = f"{path}:{line}" if line else path
            print(f"{loc}: {level} [{rule}] {msg}")
        warns = len(self.items) - fails
        print(f"\n{fails} error(s), {warns} warning(s)", file=sys.stderr)
        return 1 if fails else 0


def line_of(text: str, needle: str, default: int = 1) -> int:
    for n, ln in enumerate(text.split("\n"), 1):
        if needle in ln:
            return n
    return default


def type_label(v):
    if isinstance(v, bool):
        return "checkbox"
    if isinstance(v, (int, float)):
        return "number"
    if isinstance(v, dict):
        return "mapping"
    if isinstance(v, list):
        return "list"
    if isinstance(v, dt.datetime):
        return "datetime"
    if isinstance(v, dt.date):
        return "date"
    s = str(v)
    if ISO_UTC.match(s):
        return "datetime"
    if ISO_DATE.match(s):
        return "date"
    return "text"


def timestamp_ok(v) -> bool:
    if isinstance(v, dt.datetime):
        return v.tzinfo is not None
    return bool(ISO_UTC.match(str(v)))


def walk_timestamps(node, path=""):
    """Yield (dotted_key, value) for every key that must hold a UTC timestamp."""
    if isinstance(node, dict):
        for k, v in node.items():
            sub = f"{path}.{k}" if path else str(k)
            if k in TIMESTAMP_KEYS and not isinstance(v, (dict, list)):
                yield sub, v
            else:
                yield from walk_timestamps(v, sub)
    elif isinstance(node, list):
        for i, v in enumerate(node):
            yield from walk_timestamps(v, f"{path}[{i}]")


def as_list(v):
    if v is None:
        return []
    return v if isinstance(v, list) else [v]


def cmd_lint(args):
    r = Report()
    pages = load_pages()
    root_index = WIKI / "index.md"
    prop_types: dict[str, dict[str, str]] = {}
    inbound: dict[str, int] = {}
    concepts = {p.rel for p in pages if not p.reserved}

    for p in pages:
        rel = p.rel

        # -- C: conformance ------------------------------------------------- #
        if p.state == "unterminated":
            r.fail("C4", rel, 1, "frontmatter block is never closed by a '---' line")
            continue

        if p.path.name == "index.md":
            # OKF §8: index files carry no frontmatter; the bundle root may carry
            # only okf_version.
            if p.state == "ok":
                if p.path == root_index:
                    extra = sorted(k for k in (p.meta or {}) if k != "okf_version")
                    if extra:
                        r.fail("C2", rel, 2,
                               "root index.md may only carry okf_version, found: "
                               + ", ".join(extra))
                else:
                    r.fail("C2", rel, 1,
                           "index.md must have no frontmatter (OKF §8); only the bundle "
                           "root index.md may carry okf_version")
            elif p.path == root_index:
                r.warn("H11", rel, 1, "root index.md should declare okf_version: \"0.2\"")
        elif p.path.name == "log.md":
            pass
        else:
            if p.state != "ok":
                r.fail("C1", rel, 1, "missing YAML frontmatter block")
            elif p.meta is None:
                r.fail("C1", rel, 1, "frontmatter is not parseable YAML")
            elif not str(p.get("type") or "").strip():
                r.fail("C1", rel, 2, "frontmatter has no non-empty `type` (the only "
                                     "field OKF requires)")

        # -- O5: filenames --------------------------------------------------- #
        for part in Path(rel).parts:
            stem = part[:-3] if part.endswith(".md") else part
            if part.endswith((".py", ".sql", ".sh", ".base")):
                continue
            if not re.fullmatch(r"[a-z0-9]+(?:[-.][a-z0-9]+)*", stem):
                r.fail("O5", rel, 1,
                       f"path segment '{part}' is not lowercase kebab-case; spaces and "
                       "capitals become %20 and break links")
                break

        clean = strip_code(p.body)

        # -- O1: wikilinks ---------------------------------------------------- #
        for m in WIKILINK.finditer(clean):
            r.fail("O1", rel, line_of(p.text, m.group(0)),
                   f"wikilink [[{m.group(1)}]] is not valid OKF and renders literally "
                   "on GitHub; use [Title](../path/to/note.md)")

        # -- O2/O3/O4 + H6: links --------------------------------------------- #
        for m in MD_LINK.finditer(clean):
            bang, _text, target = m.groups()
            ln = line_of(p.text, m.group(0))
            if re.match(r"^(?:[a-z][a-z0-9+.-]*:|//|#)", target):
                continue  # external or in-page anchor
            if target.startswith("/"):
                r.fail("O4", rel, ln,
                       f"link target '{target}' starts with '/'; that breaks GitHub "
                       "rendering — use a relative path")
                continue
            if "%20" in target or " " in target:
                r.fail("O3", rel, ln, f"link target '{target}' contains an encoded or "
                                      "literal space")
            bare = target.split("#")[0]
            if not bare:
                continue
            resolved = (p.path.parent / bare).resolve()
            if bang:
                pass  # embedded asset
            elif bare.endswith("/"):
                if not resolved.is_dir():
                    r.warn("H6", rel, ln, f"link to missing directory '{target}'")
            elif not bare.endswith(".md"):
                if (p.path.parent / (bare + ".md")).is_file():
                    r.fail("O2", rel, ln,
                           f"link target '{target}' is missing its .md extension")
                elif not resolved.exists():
                    r.warn("H6", rel, ln, f"link to missing file '{target}'")
            else:
                if resolved.is_file():
                    try:
                        inbound[resolved.relative_to(WIKI).as_posix()] = \
                            inbound.get(resolved.relative_to(WIKI).as_posix(), 0) + 1
                    except ValueError:
                        pass
                else:
                    # OKF §6.1: broken links are legal — they may be knowledge not
                    # yet written. Report, never fail.
                    r.warn("H6", rel, ln, f"link to missing file '{target}'")

        # Reserved files carry no concept frontmatter, so the semantic checks below
        # do not apply to them. Their links were already checked above, which is the
        # part that matters for an index.
        if not p.meta or p.reserved:
            continue
        meta = p.meta

        # -- O6: tags --------------------------------------------------------- #
        for t in as_list(meta.get("tags")):
            if not TAG_OK.match(str(t)):
                r.fail("O6", rel, line_of(p.text, "tags:"),
                       f"tag '{t}' is not a single kebab-case token; Obsidian tags "
                       "cannot contain spaces or start with a digit")

        # -- O7: timestamps --------------------------------------------------- #
        for key, val in walk_timestamps(meta):
            if not timestamp_ok(val):
                r.fail("O7", rel, line_of(p.text, key.split(".")[-1] + ":"),
                       f"`{key}` = '{val}' has no explicit UTC offset; OKF requires "
                       "ISO 8601 like 2026-09-01T10:00:00Z")

        # -- O8: vault-global property types ---------------------------------- #
        for k, v in meta.items():
            if v is None:
                continue
            prop_types.setdefault(k, {})[rel] = type_label(v)

        # -- H1: status -------------------------------------------------------- #
        st = meta.get("status")
        if st is not None and str(st) not in STATUSES:
            r.warn("H1", rel, line_of(p.text, "status:"),
                   f"status '{st}' is not one of draft|stable|deprecated")

        # -- H2: actors -------------------------------------------------------- #
        actors = []
        gen = meta.get("generated")
        if isinstance(gen, dict) and gen.get("by"):
            actors.append(("generated.by", gen["by"]))
        for v in as_list(meta.get("verified")):
            if isinstance(v, dict) and v.get("by"):
                actors.append(("verified.by", v["by"]))
        for s in as_list(meta.get("sources")):
            if isinstance(s, dict) and s.get("author"):
                actors.append(("sources.author", s["author"]))
        for key, a in actors:
            a = str(a)
            if key == "sources.author" and a.startswith("team:"):
                continue
            if not ACTOR.match(a):
                r.warn("H2", rel, line_of(p.text, a),
                       f"`{key}` = '{a}' does not match OKF's actor convention "
                       "(human:<id>, process:<id>, or <producer>/<version>)")

        # -- H3: footnotes vs sources[].id ------------------------------------- #
        sids = {str(s["id"]) for s in as_list(meta.get("sources"))
                if isinstance(s, dict) and s.get("id")}
        refs = {m.group(1) for m in FOOTNOTE_REF.finditer(clean)}
        defs = {m.group(1) for m in FOOTNOTE_DEF.finditer(p.body)}
        for missing in sorted(refs - sids):
            r.warn("H3", rel, line_of(p.text, f"[^{missing}]"),
                   f"footnote [^{missing}] has no matching sources[].id")
        for undef in sorted(refs - defs):
            r.warn("H3", rel, line_of(p.text, f"[^{undef}]"),
                   f"footnote [^{undef}] is referenced but never defined")
        for unused in sorted(sids - refs):
            r.warn("H3", rel, line_of(p.text, f"id: {unused}"),
                   f"source '{unused}' is declared but never cited in the body")

        # -- H4: staleness ------------------------------------------------------ #
        sa = meta.get("stale_after")
        if sa is not None and timestamp_ok(sa):
            when = sa if isinstance(sa, dt.datetime) else \
                dt.datetime.fromisoformat(str(sa).replace("Z", "+00:00"))
            if when <= dt.datetime.now(dt.timezone.utc):
                r.warn("H4", rel, line_of(p.text, "stale_after:"),
                       f"stale_after {sa} has passed; this page needs re-verification")

        # -- H9: flat mirror in sync -------------------------------------------- #
        upd, gat = meta.get("updated"), (gen or {}).get("at") if isinstance(gen, dict) else None
        if upd is not None and gat is not None:
            u = upd.isoformat() if isinstance(upd, (dt.date, dt.datetime)) else str(upd)
            g = gat.isoformat() if isinstance(gat, (dt.date, dt.datetime)) else str(gat)
            if u[:10] != g[:10]:
                r.warn("H9", rel, line_of(p.text, "updated:"),
                       f"`updated` ({u[:10]}) does not mirror generated.at ({g[:10]})")

        # -- H12: trust mirror must match the tier derived from `verified` -------- #
        vlist = [v for v in as_list(meta.get("verified")) if isinstance(v, dict)]
        if not vlist:
            derived = "unverified"
        elif any(str(v.get("by", "")).startswith("human:") for v in vlist):
            derived = "human-reviewed"
        else:
            derived = "machine-confirmed"
        tr = meta.get("trust")
        if tr is None:
            r.warn("H12", rel, 2,
                   f"no `trust` mirror; the tier derived from `verified` is '{derived}'")
        elif str(tr) != derived:
            # A page claiming to be reviewed when nothing verified it is the one
            # lie that would corrupt the whole trust signal.
            r.fail("H12", rel, line_of(p.text, "trust:"),
                   f"`trust: {tr}` contradicts the tier derived from `verified` "
                   f"('{derived}')")

        # -- H10: description ---------------------------------------------------- #
        if not p.reserved and not str(meta.get("description") or "").strip():
            r.warn("H10", rel, 2,
                   "no `description`; index.md generators reuse it verbatim")

    # -- C3: log.md ------------------------------------------------------------ #
    for log in WIKI.rglob("log.md"):
        rel = log.relative_to(WIKI).as_posix()
        text = log.read_text(encoding="utf-8", errors="replace")
        dates = []
        for n, ln in enumerate(text.split("\n"), 1):
            if ln.startswith("## "):
                head = ln[3:].strip()
                if not ISO_DATE.match(head):
                    r.fail("C3", rel, n,
                           f"log heading '## {head}' must be an ISO 8601 date "
                           "(## YYYY-MM-DD), per OKF §9")
                else:
                    dates.append((head, n))
        for (a, _), (b, n) in zip(dates, dates[1:]):
            if b > a:
                r.fail("C3", rel, n,
                       f"log entries must be newest first, but {b} follows {a}")

    # -- O8: report property-type conflicts ------------------------------------ #
    for key, seen in prop_types.items():
        labels = set(seen.values())
        if len(labels) > 1:
            example = {}
            for f, lab in seen.items():
                example.setdefault(lab, f)
            detail = "; ".join(f"{lab} in {f}" for lab, f in sorted(example.items()))
            for f, lab in sorted(seen.items()):
                r.fail("O8", f, 2,
                       f"property `{key}` is used as {lab} here but Obsidian property "
                       f"types are vault-global — conflict: {detail}")

    # -- H5/H7/H8: index coverage and orphans ---------------------------------- #
    for idx in WIKI.rglob("index.md"):
        rel = idx.relative_to(WIKI).as_posix()
        text = idx.read_text(encoding="utf-8", errors="replace")
        listed = set()
        for m in MD_LINK.finditer(strip_code(text)):
            target = m.group(3).split("#")[0]
            if re.match(r"^(?:[a-z][a-z0-9+.-]*:|//|#)", target):
                continue
            resolved = (idx.parent / target).resolve()
            if target.endswith("/"):
                if resolved.is_dir():
                    listed.add(resolved)
                continue
            if resolved.is_file():
                listed.add(resolved)
            else:
                r.warn("H7", rel, line_of(text, m.group(0)),
                       f"index entry points at missing '{target}'")
        for sib in sorted(idx.parent.glob("*.md")):
            if sib.name in RESERVED or sib.resolve() in listed:
                continue
            r.warn("H8", rel, 1,
                   f"'{sib.name}' sits in this folder but is not listed in its index.md")
        for sub in sorted(idx.parent.iterdir()):
            if sub.is_dir() and any(sub.rglob("*.md")) and sub.resolve() not in listed:
                r.warn("H8", rel, 1,
                       f"subdirectory '{sub.name}/' is not listed in this index.md")

    for rel in sorted(concepts):
        if inbound.get(rel, 0) == 0:
            r.warn("H5", rel, 1, "orphan page: nothing links to it")

    return r.render(quiet=args.quiet)


# --------------------------------------------------------------------------- #
def main():
    ap = argparse.ArgumentParser(prog="wiki", description=__doc__.split("\n")[0])
    sub = ap.add_subparsers(dest="cmd", required=True)

    p = sub.add_parser("index", help="print a folder's index")
    p.add_argument("path", nargs="?", default="")
    p.set_defaults(fn=cmd_index)

    p = sub.add_parser("read", help="print one concept by id")
    p.add_argument("concept_id")
    p.set_defaults(fn=cmd_read)

    p = sub.add_parser("search", help="ranked full-text search")
    p.add_argument("query", nargs="+")
    p.add_argument("--limit", type=int, default=15)
    p.set_defaults(fn=cmd_search)

    p = sub.add_parser("list", help="list pages by frontmatter")
    p.add_argument("--type")
    p.add_argument("--tag")
    p.add_argument("--status")
    p.set_defaults(fn=cmd_list)

    p = sub.add_parser("lint", help="OKF conformance + Obsidian safety")
    p.add_argument("-q", "--quiet", action="store_true", help="errors only")
    p.set_defaults(fn=cmd_lint)

    p = sub.add_parser("stats", help="counts and the size guard")
    p.set_defaults(fn=cmd_stats)

    args = ap.parse_args()
    sys.exit(args.fn(args))


if __name__ == "__main__":
    main()
