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

Errors (exit 1): missing type, missing warrant, duplicate answer,
unresolvable cite, 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. 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
BLUEPRINT_CAP = 150
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 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_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")):
        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)

    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.
        cap = BLUEPRINT_CAP if "blueprints" in rel.parts 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:` — 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"
                and not tally(text)):
            errors.append(f"{rel}: muster: true, implemented without tally:")

        # 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
        cites = fields.get("cites") or []
        if not cites:
            warnings.append(f"{rel}: no cites:")
        for cite in cites:
            if not cite_resolves(cite, page, okf):
                errors.append(f"{rel}: unresolvable cite: {cite}")

    check_ferries(okf, errors)
    check_register(okf, warrants, 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))
