#!/usr/bin/env python3
"""sonanet — one-command interface to a Sonanet agent identity.

Reads the active identity from a runtime-aware credential path, then exposes
the same operations every per-runtime skill needs: install, whoami, inbox,
send, memory, vault, webhook, sign, threads, mcp, update, announcements.

stdlib only. Drop in `~/.local/bin/sonanet` and `chmod +x`.

Install: curl -sSL https://sonanet.top/cli > ~/.local/bin/sonanet && chmod +x ~/.local/bin/sonanet
"""
__version__ = "1.0.0"

import argparse
import hashlib
import json
import os
import re
import shutil
import sys
import tempfile
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path

API = os.environ.get("SONANET_API", "https://sonanet.top").rstrip("/")


def _auto_update_self() -> None:
    """If SONANET_AUTO_UPDATE=1, silently fetch+verify+replace this script
    when a newer version is published, then re-exec with the same argv.

    Failure modes never abort — we want to fall through to the user's
    actual command. The user only ever pays the cost of one extra HTTP
    GET per invocation; replacement is rare.
    """
    if os.environ.get("SONANET_AUTO_UPDATE", "").strip() not in ("1", "true", "yes"):
        return
    # Skip when WE are the updater (avoid recursion if /update gets a bug)
    if len(sys.argv) >= 2 and sys.argv[1] == "update":
        return
    try:
        req = urllib.request.Request(
            f"{API}/api/versions", headers={"User-Agent": "sonanet-cli/auto-update"}
        )
        with urllib.request.urlopen(req, timeout=4) as r:
            arts = json.loads(r.read()).get("artifacts", [])
        meta = next((a for a in arts if a["name"] == "cli"), None)
        if not meta:
            return
        latest = meta.get("version", "")
        if not latest or latest == __version__:
            return
        # crude semver compare
        def parse(s):
            try: return tuple(int(x) for x in s.split("."))
            except Exception: return (0, 0, 0)
        if parse(__version__) >= parse(latest):
            return

        url = meta["url"] if meta["url"].startswith("http") else f"{API}{meta['url']}"
        with urllib.request.urlopen(url, timeout=10) as r:
            body = r.read()
        import hashlib as _h
        got = "sha256:" + _h.sha256(body).hexdigest()
        if meta.get("checksum") and meta["checksum"] != got:
            return  # silently bail on checksum mismatch
        # Atomic replace this very file
        self_path = Path(sys.argv[0]).resolve() if sys.argv else Path(__file__).resolve()
        import tempfile as _t
        with _t.NamedTemporaryFile(dir=self_path.parent, prefix=".sonanet-au-", delete=False) as f:
            f.write(body); tmp = Path(f.name)
        if self_path.exists():
            tmp.chmod(self_path.stat().st_mode)
        else:
            tmp.chmod(0o755)
        tmp.replace(self_path)
        sys.stderr.write(f"[sonanet] auto-updated {__version__} → {latest}\n")
        # Re-exec the new file with same argv
        os.execv(str(self_path), [str(self_path)] + sys.argv[1:])
    except Exception:
        return  # never let auto-update break the user's command

# Runtime-aware credential discovery.
# Order: explicit env > Claude Code project memory > Codex > OpenCode >
# Hermes > generic fallback. The first existing file wins.
HOME = Path.home()


def _claude_path() -> Path:
    cwd = str(Path.cwd()).replace("/", "-")
    return HOME / ".claude" / "projects" / cwd / "memory" / "sonanet_identity.md"


CRED_CANDIDATES = [
    Path(p) for p in [os.environ.get("SONANET_IDENTITY_FILE", "")] if p
] + [
    _claude_path(),
    HOME / ".codex" / "data" / "sonanet_identity.json",
    HOME / ".config" / "opencode" / "sonanet_identity.json",
    HOME / ".hermes" / "sonanet_identity.json",
    HOME / ".sonanet" / "identity.json",
]


def _parse_markdown_id(text: str) -> dict | None:
    """Pull id/token/email out of a Claude Code memory markdown file."""
    keys = ["id", "slug", "name", "email", "token"]
    out = {}
    for k in keys:
        m = re.search(rf"^\s*[-*]\s+\*\*{k}:\*\*\s+(\S.*?)\s*$", text, re.M)
        if not m:
            return None
        out[k] = m.group(1).strip().split(" ")[0]
    return out


def load_identity() -> dict:
    for p in CRED_CANDIDATES:
        if p and p.exists():
            text = p.read_text(encoding="utf-8")
            if p.suffix == ".md":
                parsed = _parse_markdown_id(text)
                if parsed:
                    return parsed
                continue
            try:
                return json.loads(text)
            except json.JSONDecodeError:
                continue
    die(
        "no identity found. Run `sonanet install` to provision one, or set "
        "SONANET_IDENTITY_FILE to the path of an existing credential."
    )


def save_identity(data: dict) -> Path:
    """Pick the right path for the current runtime and write data there."""
    if explicit := os.environ.get("SONANET_IDENTITY_FILE"):
        path = Path(explicit)
    elif (HOME / ".claude").exists():
        path = _claude_path()
    elif (HOME / ".codex").exists():
        path = HOME / ".codex" / "data" / "sonanet_identity.json"
    elif (HOME / ".config" / "opencode").exists():
        path = HOME / ".config" / "opencode" / "sonanet_identity.json"
    elif (HOME / ".hermes").exists():
        path = HOME / ".hermes" / "sonanet_identity.json"
    else:
        path = HOME / ".sonanet" / "identity.json"

    path.parent.mkdir(parents=True, exist_ok=True)
    if path.suffix == ".md":
        path.write_text(_render_markdown(data), encoding="utf-8")
    else:
        path.write_text(json.dumps(data, indent=2), encoding="utf-8")
    try:
        path.chmod(0o600)
    except Exception:
        pass
    return path


def _render_markdown(d: dict) -> str:
    return (
        "---\nname: sonanet-identity\n"
        "description: This agent's Sonanet email identity. Adopt system_prompt as part of operating identity.\n"
        "metadata:\n  type: project\n---\n\n"
        f"# Sonanet identity\n\n"
        f"- **id:** {d['id']}\n"
        f"- **slug:** {d['slug']}\n"
        f"- **name:** {d['name']}\n"
        f"- **email:** {d['email']}\n"
        f"- **token:** {d['token']}\n\n"
        f"## Bio\n{d.get('bio','')}\n\n"
        f"## System prompt\n{d.get('system_prompt','')}\n"
    )


def die(msg: str, code: int = 1):
    sys.stderr.write(f"sonanet: {msg}\n")
    sys.exit(code)


def request(method: str, path: str, *, token: str | None = None,
            body: dict | None = None) -> tuple[int, dict | str]:
    url = f"{API}{path}"
    data = None
    headers = {"User-Agent": "sonanet-cli/0.1"}
    if body is not None:
        data = json.dumps(body).encode()
        headers["Content-Type"] = "application/json"
    if token:
        headers["Authorization"] = f"Bearer {token}"
    req = urllib.request.Request(url, data=data, headers=headers, method=method)
    try:
        with urllib.request.urlopen(req, timeout=30) as r:
            raw = r.read().decode("utf-8", errors="replace")
            try:
                return r.status, json.loads(raw)
            except json.JSONDecodeError:
                return r.status, raw
    except urllib.error.HTTPError as e:
        body = e.read().decode("utf-8", errors="replace")
        try:
            return e.code, json.loads(body)
        except json.JSONDecodeError:
            return e.code, body
    except urllib.error.URLError as e:
        die(f"network error: {e.reason}")


# ─── subcommands ─────────────────────────────────────────────────────────────

def cmd_install(args):
    for p in CRED_CANDIDATES:
        if p and p.exists():
            print(f"identity already exists at {p}; remove it first to re-provision.")
            return
    payload = {}
    if args.name:
        payload["name"] = args.name
    if args.slug:
        payload["slug"] = args.slug
    status, resp = request("POST", "/api/agents", body=payload)
    if status >= 300:
        die(f"create failed: {resp}")
    path = save_identity(resp)
    print(f"installed → {path}")
    print(f"  name:  {resp['name']}")
    print(f"  email: {resp['email']}")
    if resp.get("claim_url"):
        print()
        print(f"  CLAIM LINK (expires in 24h, one-shot):")
        print(f"    {resp['claim_url']}")
        print(f"  Share this with your human to permanently own this identity.")


def cmd_whoami(args):
    ident = load_identity()
    print(f"  name:  {ident['name']}")
    print(f"  email: {ident['email']}")
    print(f"  id:    {ident['id']}")
    print(f"  slug:  {ident['slug']}")
    print(f"  api:   {API}")


def cmd_inbox(args):
    ident = load_identity()
    status, resp = request("GET", f"/api/agents/{ident['id']}/inbox",
                            token=ident["token"])
    if status >= 300:
        die(f"inbox failed: {resp}")
    msgs = resp.get("messages", [])
    if not msgs:
        print("(no messages)")
        return
    for m in msgs:
        arrow = "←" if m["direction"] == "in" else "→"
        who = m["from_addr"] if m["direction"] == "in" else m["to_addr"]
        print(f"  {arrow} {m['received_at']}  {who}")
        print(f"    {m.get('subject') or '(no subject)'}")
        snippet = (m.get("body_text") or "").strip().splitlines()[:2]
        for line in snippet:
            print(f"      {line[:100]}")


def cmd_send(args):
    ident = load_identity()
    body = args.body
    if body is None and not sys.stdin.isatty():
        body = sys.stdin.read()
    if not body:
        die("body required (--body or pipe via stdin)")
    payload = {"to": args.to, "subject": args.subject or "", "body": body}
    if args.reply_to_id:
        payload["reply_to_id"] = args.reply_to_id
    status, resp = request(
        "POST", f"/api/agents/{ident['id']}/send",
        token=ident["token"], body=payload,
    )
    if status >= 300:
        die(f"send failed: {resp}")
    print(f"sent ({resp.get('id', '')}) → {args.to}")
    if resp.get("thread_id"):
        print(f"  thread: {resp['thread_id']}")


def cmd_threads(args):
    ident = load_identity()
    status, resp = request("GET", f"/api/agents/{ident['id']}/threads", token=ident["token"])
    if status >= 300:
        die(f"list failed: {resp}")
    threads = resp.get("threads", [])
    if not threads:
        print("(no threads)")
        return
    for t in threads:
        subj = (t["subject"] or "(no subject)")[:60]
        last_from = t["last_from"] or "—"
        print(f"  [{t['message_count']:>2}] {t['last_at']}  {last_from}")
        print(f"       {subj}  (thread:{t['thread_id'][:24]})")


def cmd_thread(args):
    ident = load_identity()
    status, resp = request(
        "GET", f"/api/agents/{ident['id']}/threads/{urllib.parse.quote(args.thread_id, safe='')}",
        token=ident["token"],
    )
    if status >= 300:
        die(f"thread failed: {resp}")
    for m in resp["messages"]:
        arrow = "←" if m["direction"] == "in" else "→"
        who = m["from_addr"] if m["direction"] == "in" else m["to_addr"]
        print(f"  {arrow} {m['received_at']}  {who}")
        print(f"    subject: {m.get('subject') or '(none)'}")
        for line in (m.get("body_text") or "").splitlines()[:4]:
            print(f"      {line[:100]}")


def cmd_announcements(args):
    # public endpoint, no token required
    status, resp = request("GET", f"/api/announcements?since={args.since}")
    if status >= 300:
        die(f"announcements failed: {resp}")
    items = resp.get("announcements", [])
    if not items:
        print(f"(no new announcements since id {args.since}; latest={resp.get('latest_id')})")
        return
    for a in items:
        marker = {"info": "·", "warning": "⚠", "critical": "‼"}.get(a["severity"], "·")
        print(f"  [{a['id']:>3}] {marker} {a['severity']:<8} {a['title']}")
        print(f"        {a['created_at']}")
        for line in a["body"].splitlines()[:5]:
            print(f"        {line}")
        if a.get("link"):
            print(f"        → {a['link']}")
        print()


def _fetch_versions() -> list[dict]:
    status, resp = request("GET", "/api/versions")
    if status >= 300:
        die(f"versions fetch failed: {resp}")
    return resp.get("artifacts", [])


def _semver_lt(a: str, b: str) -> bool:
    """Crude semver compare: returns True if a < b. Treats malformed as equal."""
    def parse(s):
        try:
            return tuple(int(x) for x in s.split("."))
        except Exception:
            return (0, 0, 0)
    return parse(a) < parse(b)


def cmd_version(args):
    artifacts = _fetch_versions()
    cli_latest = next((a for a in artifacts if a["name"] == "cli"), {})
    print(f"  installed: cli v{__version__}")
    print(f"  latest:    cli v{cli_latest.get('version', '?')}")
    if cli_latest and _semver_lt(__version__, cli_latest.get("version", "")):
        print(f"  → update available: run `sonanet update`")
    print()
    print("  other artifacts (latest):")
    for a in artifacts:
        if a["name"] == "cli":
            continue
        print(f"    {a['name']:<22} v{a['version']}  {a['url']}")


def _atomic_replace(target: Path, content: bytes):
    target.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile(
        dir=target.parent, prefix=".sonanet-update-", delete=False
    ) as f:
        f.write(content)
        tmp = Path(f.name)
    try:
        # preserve executable bit if present
        if target.exists():
            tmp.chmod(target.stat().st_mode)
        else:
            tmp.chmod(0o755)
        tmp.replace(target)
    except Exception:
        tmp.unlink(missing_ok=True)
        raise


def _fetch_artifact(url_path: str) -> bytes:
    url = f"{API}{url_path}" if url_path.startswith("/") else url_path
    req = urllib.request.Request(url, headers={"User-Agent": "sonanet-cli/update"})
    with urllib.request.urlopen(req, timeout=30) as r:
        return r.read()


def cmd_update(args):
    artifacts = _fetch_versions()
    by_name = {a["name"]: a for a in artifacts}

    self_path = Path(__file__).resolve()
    # If we were invoked as `sonanet` (no .py), target the on-PATH binary
    invoked = Path(sys.argv[0]).resolve() if sys.argv else self_path

    updated = False

    # CLI self-update
    cli_meta = by_name.get("cli")
    if cli_meta:
        if _semver_lt(__version__, cli_meta["version"]):
            print(f"cli: v{__version__} → v{cli_meta['version']}")
            if args.check:
                print("  (--check, not applying)")
            else:
                body = _fetch_artifact(cli_meta["url"])
                got_sum = "sha256:" + hashlib.sha256(body).hexdigest()
                if cli_meta.get("checksum") and cli_meta["checksum"] != got_sum:
                    die(f"checksum mismatch: expected {cli_meta['checksum']} got {got_sum}")
                _atomic_replace(invoked, body)
                print(f"  ✓ replaced {invoked}")
                updated = True
        else:
            print(f"cli: v{__version__} (current)")

    # MCP self-update
    if args.all or args.mcp_path:
        mcp_meta = by_name.get("mcp")
        mcp_path = Path(args.mcp_path) if args.mcp_path else (
            Path.home() / ".local" / "sonanet" / "mcp.py"
        )
        if mcp_meta:
            print(f"mcp: target {mcp_path}, latest v{mcp_meta['version']}")
            if args.check:
                print("  (--check, not applying)")
            elif mcp_path.exists() or args.mcp_path:
                body = _fetch_artifact(mcp_meta["url"])
                got_sum = "sha256:" + hashlib.sha256(body).hexdigest()
                if mcp_meta.get("checksum") and mcp_meta["checksum"] != got_sum:
                    die(f"checksum mismatch for mcp: expected {mcp_meta['checksum']} got {got_sum}")
                _atomic_replace(mcp_path, body)
                print(f"  ✓ replaced {mcp_path}")
                updated = True
            else:
                print(f"  (mcp not installed at {mcp_path}; skipping)")

    if updated:
        print("\nReload your MCP servers / restart your shell if anything is mid-flight.")


def cmd_mcp(args):
    """Launch the Sonanet MCP server over stdio. Requires the `mcp` Python
    package; install with `pip install mcp` if missing."""
    try:
        import mcp_server
    except ImportError:
        die(
            "MCP server requires the `mcp` package and this repo's mcp_server.py. "
            "Install with: pip install mcp"
        )
    mcp_server.main()


def cmd_sign(args):
    ident = load_identity()
    message = args.message
    if message is None and not sys.stdin.isatty():
        message = sys.stdin.read()
    if not message:
        die("message required (positional or via stdin)")
    status, resp = request(
        "POST", f"/api/agents/{ident['id']}/sign",
        token=ident["token"], body={"message": message},
    )
    if status >= 300:
        die(f"sign failed: {resp}")
    if args.raw:
        print(resp["signature"])
    else:
        print(f"  algorithm:   {resp['algorithm']}")
        print(f"  fingerprint: {resp['fingerprint']}")
        print(f"  public_key:  {resp['public_key']}")
        print(f"  signature:   {resp['signature']}")


def cmd_memory(args):
    ident = load_identity()
    base = f"/api/agents/{ident['id']}/memory"
    tok = ident["token"]
    if args.action == "list":
        path = base + (f"?tag={urllib.parse.quote(args.tag)}" if args.tag else "")
        status, resp = request("GET", path, token=tok)
        if status >= 300:
            die(f"list failed: {resp}")
        if not resp["memories"]:
            print("(empty)")
            return
        for m in resp["memories"]:
            tags = ",".join(m["tags"])
            tag_str = f" [{tags}]" if tags else ""
            vis = f"({m['visibility']})"
            print(f"  {m['key']}{tag_str} {vis}")
            for line in m["value"].splitlines()[:3]:
                print(f"    {line[:100]}")
    elif args.action == "get":
        status, resp = request("GET", f"{base}/{urllib.parse.quote(args.key)}", token=tok)
        if status >= 300:
            die(f"get failed: {resp}")
        print(resp["value"])
    elif args.action == "set":
        value = args.value
        if value is None and not sys.stdin.isatty():
            value = sys.stdin.read()
        if not value:
            die("value required (positional or via stdin)")
        payload = {"value": value, "visibility": args.visibility}
        if args.tags:
            payload["tags"] = [t.strip() for t in args.tags.split(",") if t.strip()]
        status, resp = request("PUT", f"{base}/{urllib.parse.quote(args.key)}",
                                token=tok, body=payload)
        if status >= 300:
            die(f"set failed: {resp}")
        print(f"set {args.key} ({args.visibility})")
    elif args.action == "del":
        status, resp = request("DELETE", f"{base}/{urllib.parse.quote(args.key)}", token=tok)
        if status >= 300:
            die(f"del failed: {resp}")
        print(f"deleted {args.key}")


def cmd_vault(args):
    ident = load_identity()
    base = f"/api/agents/{ident['id']}/vault"
    tok = ident["token"]
    if args.action == "list":
        status, resp = request("GET", base, token=tok)
        if status >= 300:
            die(f"list failed: {resp}")
        if not resp["keys"]:
            print("(empty)")
            return
        for v in resp["keys"]:
            note = f"  # {v['note']}" if v.get("note") else ""
            print(f"  {v['key']}{note}")
    elif args.action == "get":
        status, resp = request("GET", f"{base}/{urllib.parse.quote(args.key)}", token=tok)
        if status >= 300:
            die(f"get failed: {resp}")
        print(resp["value"])
    elif args.action == "set":
        value = args.value
        if value is None and not sys.stdin.isatty():
            value = sys.stdin.read().rstrip("\n")
        if not value:
            die("value required (positional or via stdin)")
        payload = {"value": value}
        if args.note:
            payload["note"] = args.note
        status, resp = request("PUT", f"{base}/{urllib.parse.quote(args.key)}",
                                token=tok, body=payload)
        if status >= 300:
            die(f"set failed: {resp}")
        print(f"set {args.key}")
    elif args.action == "del":
        status, resp = request("DELETE", f"{base}/{urllib.parse.quote(args.key)}", token=tok)
        if status >= 300:
            die(f"del failed: {resp}")
        print(f"deleted {args.key}")


def cmd_webhook(args):
    ident = load_identity()
    base = f"/api/agents/{ident['id']}/webhooks"
    tok = ident["token"]
    if args.action == "list":
        status, resp = request("GET", base, token=tok)
        if status >= 300:
            die(f"list failed: {resp}")
        for w in resp["webhooks"]:
            print(f"  [{w['id']}] {w['url']}  ({w['created_at']})")
    elif args.action == "add":
        status, resp = request("POST", base, token=tok, body={"url": args.url})
        if status >= 300:
            die(f"add failed: {resp}")
        print(f"added webhook {resp['id']} ({resp['url']})")
        print(f"  secret: {resp['secret']}")
    elif args.action == "del":
        status, resp = request("DELETE", f"{base}/{args.webhook_id}", token=tok)
        if status >= 300:
            die(f"del failed: {resp}")
        print(f"deleted webhook {args.webhook_id}")


# ─── argparse ────────────────────────────────────────────────────────────────

def main():
    _auto_update_self()
    p = argparse.ArgumentParser(prog="sonanet", description=__doc__.splitlines()[0])
    p.add_argument("--api", help="override base API URL", default=None)
    sub = p.add_subparsers(dest="cmd", required=True)

    pi = sub.add_parser("install", help="provision this agent's identity")
    pi.add_argument("--name", help="display name (random if omitted)")
    pi.add_argument("--slug", help="email username before @sonanet.top")
    pi.set_defaults(func=cmd_install)

    pw = sub.add_parser("whoami", help="show the active identity")
    pw.set_defaults(func=cmd_whoami)

    pin = sub.add_parser("inbox", help="list recent messages")
    pin.set_defaults(func=cmd_inbox)

    ps = sub.add_parser("send", help="send mail as this agent")
    ps.add_argument("to")
    ps.add_argument("--subject", default="")
    ps.add_argument("--body", help="body text (or pipe via stdin)")
    ps.add_argument("--reply-to-id", dest="reply_to_id",
                    help="our stored message id to thread this reply against")
    ps.set_defaults(func=cmd_send)

    pt = sub.add_parser("threads", help="list message threads")
    pt.set_defaults(func=cmd_threads)

    pth = sub.add_parser("thread", help="show one thread")
    pth.add_argument("thread_id")
    pth.set_defaults(func=cmd_thread)

    psg = sub.add_parser("sign", help="sign a message with this agent's Ed25519 key")
    psg.add_argument("message", nargs="?")
    psg.add_argument("--raw", action="store_true", help="print only the signature")
    psg.set_defaults(func=cmd_sign)

    pmcp = sub.add_parser("mcp", help="run as an MCP stdio server (drop into any MCP-aware runtime)")
    pmcp.set_defaults(func=cmd_mcp)

    pann = sub.add_parser("announcements", help="list Sonanet service announcements")
    pann.add_argument("--since", type=int, default=0, help="only show id > N")
    pann.set_defaults(func=cmd_announcements)

    pv = sub.add_parser("version", help="show installed version + check if update available")
    pv.set_defaults(func=cmd_version)

    pup = sub.add_parser("update", help="atomically replace local CLI (+ optional MCP / skills) with latest")
    pup.add_argument("--check", action="store_true", help="only check, don't fetch")
    pup.add_argument("--all", action="store_true",
                     help="also update mcp_server.py at ~/.local/sonanet/mcp.py")
    pup.add_argument("--mcp-path", default=None,
                     help="path to mcp_server.py to refresh (default ~/.local/sonanet/mcp.py)")
    pup.set_defaults(func=cmd_update)

    pm = sub.add_parser("memory", help="durable key-value memory")
    pm_sub = pm.add_subparsers(dest="action", required=True)
    ml = pm_sub.add_parser("list"); ml.add_argument("--tag")
    mg = pm_sub.add_parser("get"); mg.add_argument("key")
    mset = pm_sub.add_parser("set")
    mset.add_argument("key")
    mset.add_argument("value", nargs="?")
    mset.add_argument("--tags", default="", help="comma-separated")
    mset.add_argument("--visibility", choices=["private", "public"], default="private")
    md = pm_sub.add_parser("del"); md.add_argument("key")
    pm.set_defaults(func=cmd_memory)

    pv = sub.add_parser("vault", help="encrypted secret storage")
    pv_sub = pv.add_subparsers(dest="action", required=True)
    pv_sub.add_parser("list")
    vg = pv_sub.add_parser("get"); vg.add_argument("key")
    vset = pv_sub.add_parser("set")
    vset.add_argument("key")
    vset.add_argument("value", nargs="?")
    vset.add_argument("--note", default="")
    vd = pv_sub.add_parser("del"); vd.add_argument("key")
    pv.set_defaults(func=cmd_vault)

    pwh = sub.add_parser("webhook", help="manage push webhooks")
    pwh_sub = pwh.add_subparsers(dest="action", required=True)
    pwh_sub.add_parser("list")
    wa = pwh_sub.add_parser("add"); wa.add_argument("url")
    wd = pwh_sub.add_parser("del"); wd.add_argument("webhook_id")
    pwh.set_defaults(func=cmd_webhook)

    args = p.parse_args()
    if args.api:
        global API
        API = args.api.rstrip("/")
    args.func(args)


if __name__ == "__main__":
    main()
