#!/usr/bin/env python3
"""get — fetch the Multimem kit from the Any website and register it with a host.

    curl -fsSL https://any.org/assets/multimem/get.py | python3 - --host claude-code

Options:
  --host claude-code|codex|mcp|rules|none   what to register after downloading (default none)
  --dest DIR      where the kit lands (default: ~/.claude/skills/multimem for claude-code, else ~/.multimem/kit)
  --base URL      where to fetch from (default https://any.org/assets/multimem)
  --write FILE    passed to `install --host mcp|rules`
  --no-install    download and verify only

Stdlib only, python3 >= 3.9. Every file is checked against the sha256 in manifest.json before it is written;
a mismatch aborts the whole download and leaves an existing kit untouched.
"""

import argparse
import hashlib
import json
import os
import pathlib
import subprocess
import sys
import urllib.request

DEFAULT_BASE = "https://any.org/assets/multimem"


def fetch(url):
    req = urllib.request.Request(url, headers={"User-Agent": "multimem-get/1"})
    with urllib.request.urlopen(req, timeout=60) as r:
        return r.read()


def main(argv=None):
    ap = argparse.ArgumentParser(prog="get.py", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--host", choices=["claude-code", "codex", "mcp", "rules", "none"], default="none")
    ap.add_argument("--dest")
    ap.add_argument("--base", default=os.environ.get("MULTIMEM_BASE_URL") or DEFAULT_BASE)
    ap.add_argument("--write")
    ap.add_argument("--no-install", action="store_true")
    args = ap.parse_args(argv)
    if args.dest:
        dest = pathlib.Path(args.dest).expanduser()
    elif args.host == "claude-code":
        dest = pathlib.Path(os.environ.get("CLAUDE_CONFIG_DIR") or (pathlib.Path.home() / ".claude")) / "skills" / "multimem"
    else:
        dest = pathlib.Path(os.environ.get("MULTIMEM_HOME") or (pathlib.Path.home() / ".multimem")) / "kit"
    base = args.base.rstrip("/")
    manifest = json.loads(fetch(base + "/manifest.json").decode("utf-8"))
    files = {}
    for f in manifest["files"]:
        data = fetch("%s/%s" % (base, f["name"]))
        got = hashlib.sha256(data).hexdigest()
        if got != f["sha256"]:
            print("checksum mismatch for %s (got %s, manifest %s); nothing written" % (f["name"], got[:12], f["sha256"][:12]), file=sys.stderr)
            return 1
        files[f["name"]] = data
    dest.mkdir(parents=True, exist_ok=True)
    for name, data in files.items():
        (dest / name).write_bytes(data)
    (dest / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
    print("multimem %s: %d files in %s" % (manifest.get("version", "?"), len(files), dest), file=sys.stderr)
    if args.no_install or args.host == "none":
        print("next: read %s for host registration, then run python3 %s doctor to verify the server and space. Use ensure without --create for a verified existing space; --create is only for an explicitly requested fresh space." % (dest / "INSTALL.md", dest / "multimem.py"), file=sys.stderr)
        return 0
    cmd = [sys.executable, str(dest / "multimem.py"), "install", "--host", args.host]
    if args.write:
        cmd += ["--write", args.write]
    return subprocess.call(cmd)


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