#!/usr/bin/env python3
"""okfmem — thin CLI dispatcher for the memory engine.

Usage:
  okfmem backfill    [--dry-run] [--store PATH]  # P1: stamp decay frontmatter
  okfmem init        [--dry-run] [--status] ...  # P2: pointers + registry
  okfmem consolidate [--dry-run] ...             # P3: decay + archive + push
  okfmem sync        -m "<msg>" [--no-push] [--author "name <email>"] ...
                                                 # commit + pull-rebase + push
  okfmem pull        [--quiet] [--store PATH]    # read-side sync: fetch + integrate, no commit needed
                                                 # both honour $OKFMEM_GIT_TOKEN[_<NAME>] — #140
  okfmem update      [--check] [--store PATH]    # git pull the engine + re-run init
  okfmem status                                  # alias for `init --status`
  okfmem graduate <slug> [--to PATH] [--dry-run] # promote a page into CLAUDE.md/
                                                 # AGENTS.md + archive the source — #10
  okfmem reindex [--report|--verify|--budget-check] [DIR]
                                                 # read-only: where the auto-loaded
                                                 # bytes sit, link integrity across
                                                 # every MEMORY*.md, and pointer
                                                 # lines over the char budget — #54
  okfmem find <term>... [--repo NAME] [--archive] [--json]
                                                 # read-only: rank pages by name,
                                                 # description, labels, then body
  okfmem export --repo NAME --out DIR [--label LABEL]... [--archive] [--dry-run] [--json] [--store PATH]
                                                 # one repo's pages as a bundle a
                                                 # teammate imports via the inbox — #149
  okfmem capture --stdin-hook | --catch-up | --now --harness H [--session ID]
                 [--transcript PATH] [--focus FILE] [--store PATH]
                                                 # queue a session for background capture
                                                 # on a cheap, tool-less model — #184
  okfmem --version                               # also `okfmem version`
  okfmem inbox push <dir> --source NAME [--repo R] [--ref T] [--machine M] [--json]
  okfmem inbox pull                              # candidate pages pushed from
  okfmem inbox review [--into STORE]             # other machines; nothing is
                      [--threshold N] [--each]   # imported without review — #84;
                      [--web [--dir DIR]]        # --web: a local browser page — #167
  okfmem inbox import [--into STORE] [--non-interactive --policy FILE [--json]]
                                                 # policy import into an attached store — #141
  okfmem inbox dump --out DIR [--into STORE] [--json]
                                                 # read-only: pending pages -> DIR/pending.jsonl
  okfmem inbox apply DIR/decisions.json [--into STORE] [--yes]
                                                 # validate, confirm, write, clear refs — #165
  okfmem migrate-to-labels [--dry-run] [--store PATH]
                                                 # flatten projects/ into pages/
                                                 # with injected repo labels — #100
  okfmem store merge <source> [--dry-run] [--yes] [--preserve-history]
                                                 # import another store; a differing
                                                 # page is kept as <path>.orphan — #78
  okfmem store split --projects a,b --dest PATH [--delete-source] [--dry-run] [--yes]
                                                 # copy projects into another store;
                                                 # --delete-source asks you to type SPLIT
  okfmem state check [--project P] [--session ID|--since S --hash H]
                                                 # read-only: guard state file
                                                 # against baseline differences

Core subcommands map to the memory_*.py modules living beside this script. Store
is resolved by each module: --store, else $OKFMEM_STORE, else ~/okfmem-store.

OPT-IN plugins live in plugins/memory_<cmd>.py and route lazily — the core map
stays harness-agnostic, so an unknown command loads a plugin only if that file
exists. Session search (issue #2) ships this way:
  okfmem index  [--rebuild]        # build FTS5 index over harness transcripts
  okfmem search "<query>"          # query it (off-prompt)
  okfmem distill [--project NAME]  # propose durable pages from recurring session
                                   # signal (report only; writes nothing) — #7
  okfmem mcp serve --stdio | --http HOST:PORT --access-team T --access-aud A
                   --allow-email E... --read-label L...
                                   # MCP server: stdio locally, Cloudflare
                                   # Access-gated HTTP remotely; writes only
                                   # to the inbox — #147
"""
import os
import runpy
import subprocess
import sys

HERE = os.path.dirname(os.path.realpath(__file__))  # realpath: resolve symlink -> real engine dir
MODULES = {"backfill": "memory_backfill.py", "init": "memory_init.py",
           "consolidate": "memory_consolidate.py", "sync": "memory_sync.py",
           "pull": "memory_pull.py", "update": "memory_update.py",
           "graduate": "memory_graduate.py", "reindex": "memory_reindex.py",
           "inbox": "memory_inbox.py", "migrate-to-labels": "memory_migrate.py",
           "state": "memory_state.py", "find": "memory_find.py",
           "store": "memory_store.py", "export": "memory_export.py",
           "capture": "memory_capture.py"}
# Opt-in plugin commands -> plugins/<file>. Loaded ONLY if the file is present,
# so core install stays harness-agnostic. Several commands may share one plugin.
PLUGINS = {"index": "memory_search.py", "search": "memory_search.py",
           "distill": "memory_distill.py", "mcp": "memory_mcp.py"}


def version_line():
    with open(os.path.join(HERE, "VERSION"), encoding="utf-8") as f:
        version = f.read().strip()
    try:
        env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
        r = subprocess.run(["git", "-C", HERE, "rev-parse", "--show-toplevel",
                            "--short", "HEAD"], capture_output=True, text=True,
                           timeout=10, env=env)
        lines = r.stdout.splitlines()
        root = os.path.normcase(os.path.realpath(lines[0])) if lines else ""
        commit = (lines[1].strip() if r.returncode == 0 and len(lines) == 2
                  and root == os.path.normcase(HERE) else "")
    except (OSError, subprocess.TimeoutExpired):
        commit = ""
    return f"okfmem {version} ({commit or 'unknown'})"


def main():
    argv = sys.argv[1:]
    if not argv or argv[0] in ("-h", "--help"):
        print(__doc__)
        sys.exit(0)
    if argv[0] in ("--version", "version"):
        print(version_line())
        sys.exit(0)

    cmd, rest = argv[0], argv[1:]
    if cmd == "status":
        cmd, rest = "init", ["--status"] + rest

    if cmd in MODULES:
        target = os.path.join(HERE, MODULES[cmd])
    elif cmd in PLUGINS and os.path.exists(os.path.join(HERE, "plugins", PLUGINS[cmd])):
        # keep the subcommand token so the plugin's own parser sees `index`/`search`
        target = os.path.join(HERE, "plugins", PLUGINS[cmd])
        rest = [cmd] + rest
    else:
        print(f"okfmem: unknown command '{cmd}'\n{__doc__}", file=sys.stderr)
        sys.exit(2)

    sys.argv = [os.path.basename(target)] + rest
    runpy.run_path(target, run_name="__main__")


if __name__ == "__main__":
    main()
