#!/usr/bin/env python3
r"""Install buzz, buzz-acp, buzz-agent and run Codex / Claude Code / Agy as Buzz agents.

HOW TO RUN (as root; the agents run as --agent-user):

  First time (generates a Nostr key per agent, prints the pubkeys, waits until
  you add them to the relay, sets each agent's profile, starts the services):

    sudo ./buzz-acp-install.py --agent-user <user> \
        --owner-pubkey <npub1xxxx...> \
        --buzz-relay-url wss://buzz.example.com \
        --setup-profile --restart-service

  Later runs (upgrade binaries / re-apply config; keys are reused): the same
  command without --setup-profile.

--owner-pubkey is YOUR Nostr public key (npub1... or 64-char hex): Buzz Desktop
-> Profile -> Identity -> Public key. Agents answer only you and each other.
Re-running is safe: files are rewritten only when their content changed.
"""

import argparse
import grp
import io
import json
import os
import platform
import pwd
import secrets
import shutil
import socket
import subprocess
import sys
import tarfile
import tempfile
import urllib.request

API_URL = "https://api.github.com/repos/block/buzz/releases/latest"
INSTALL_DIR = "/usr/local/bin"
UNIT_DIR = "/etc/systemd/system"
TARGET_BINARIES = ("buzz", "buzz-acp", "buzz-agent")
VERSION_STAMP = os.path.join(INSTALL_DIR, ".buzz-version")
DEFAULT_AGENT_USER = "agent"

# ---- nostr keys: secp256k1 pubkey + bech32 (stdlib only) -------------------
_P = 2**256 - 2**32 - 977
_N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
_G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
      0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)
_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"


def fail(msg):
    print(f"error: {msg}", file=sys.stderr)
    sys.exit(1)


def _ec_add(a, b):
    if a is None or b is None:
        return a or b
    if a[0] == b[0] and (a[1] + b[1]) % _P == 0:
        return None
    if a == b:
        lam = 3 * a[0] * a[0] * pow(2 * a[1], -1, _P) % _P
    else:
        lam = (b[1] - a[1]) * pow(b[0] - a[0], -1, _P) % _P
    x = (lam * lam - a[0] - b[0]) % _P
    return x, (lam * (a[0] - x) - a[1]) % _P


def pubkey_from_private(priv_hex):
    """x-only (nostr) pubkey hex for a 64-char hex private key."""
    k, point, addend = int(priv_hex, 16), None, _G
    if not 0 < k < _N:
        fail("private key out of range")
    while k:
        if k & 1:
            point = _ec_add(point, addend)
        addend = _ec_add(addend, addend)
        k >>= 1
    return f"{point[0]:064x}"


def _bech32_checksum(hrp, data):
    values = [ord(c) >> 5 for c in hrp] + [0] + [ord(c) & 31 for c in hrp] + data
    chk = 1
    for v in values:
        top = chk >> 25
        chk = (chk & 0x1FFFFFF) << 5 ^ v
        for i, g in enumerate((0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3)):
            chk ^= g if (top >> i) & 1 else 0
    return chk


def _convert_bits(data, src, dst):
    acc = bits = 0
    out = []
    for v in data:
        acc = acc << src | v
        bits += src
        while bits >= dst:
            bits -= dst
            out.append(acc >> bits & (1 << dst) - 1)
    if bits and src == 8:
        out.append(acc << (dst - bits) & (1 << dst) - 1)
    return out


def bech32_encode(hrp, hex_str):
    data = _convert_bits(bytes.fromhex(hex_str), 8, 5)
    chk = _bech32_checksum(hrp, data + [0] * 6) ^ 1
    tail = [(chk >> 5 * (5 - i)) & 31 for i in range(6)]
    return hrp + "1" + "".join(_CHARSET[d] for d in data + tail)


def to_hex(value, hrp):
    """64-char hex or bech32 (npub/nsec) -> lowercase hex."""
    value = value.strip().lower()
    if len(value) == 64 and all(c in "0123456789abcdef" for c in value):
        return value
    head, _, body = value.rpartition("1")
    if head == hrp and all(c in _CHARSET for c in body):
        data = [_CHARSET.index(c) for c in body]
        if _bech32_checksum(hrp, data) == 1:
            raw = bytes(_convert_bits(data[:-6], 5, 8))
            if len(raw) == 32:
                return raw.hex()
    fail(f"expected 64-char hex or a valid {hrp}1... value")


def read_key(env_path):
    try:
        for line in open(env_path):
            if line.startswith("BUZZ_PRIVATE_KEY="):
                return to_hex(line.split("=", 1)[1].strip('"\n '), "nsec")
    except OSError:
        pass
    return None


# ---- agents ----------------------------------------------------------------
# One entry per ACP. Wrappers follow the machine's own style: exec npx -y <pkg>.
ACP_REGISTRY = {
    "codex": {
        "agent_command": "codex-acp",
        "wrapper": 'exec npx -y @agentclientprotocol/codex-acp@latest "$@"\n',
        "description": "Codex",
        "profile_name": "codex",
        # codex-acp defaults to a no-network sandbox, so `buzz` couldn't reply.
        "env": {"INITIAL_AGENT_MODE": "agent-full-access"},
        "unit_lines": [],
    },
    "claude-code": {
        "agent_command": "claude-cli-acp",
        # Uses the logged-in Claude Code subscription, never API billing.
        "wrapper": "unset ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN\n"
                   'exec npx -y @agentclientprotocol/claude-agent-acp@latest "$@"\n',
        "description": "Claude Code",
        "profile_name": "claude",
        "env": {},
        "unit_lines": ["UnsetEnvironment=ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN"],
    },
    "agy-cli": {
        "agent_command": "agy-cli-acp",
        # The adapter runs plain `agy` from PATH (ignores AGY_BIN).
        "wrapper": 'exec npx -y agy-agent-acp@latest "$@"\n',
        "description": "Agy CLI",
        "profile_name": "agy",
        "env": {},
        "unit_lines": [],
    },
}

# buzz-acp settings for every service (see `buzz-acp --help`).
COMMON_ENV = {
    "BUZZ_ACP_AGENT_ARGS": "",
    "BUZZ_ACP_PERMISSION_MODE": "bypass-permissions",
    "BUZZ_ACP_RESPOND_TO": "allowlist",
    "BUZZ_ACP_ALLOWED_RESPOND_TO": "owner-only,allowlist",
    "BUZZ_ACP_SUBSCRIBE": "mentions",
    "BUZZ_ACP_SESSION_POLICY": "thread",
    "BUZZ_ACP_MULTIPLE_EVENT_HANDLING": "steer",
    "BUZZ_ACP_DEDUP": "queue",
    "BUZZ_ACP_AGENTS": "1",
    "BUZZ_ACP_MAX_TURN_DURATION": "7200",
    "BUZZ_ACP_IDLE_TIMEOUT": "1800",
    "BUZZ_ACP_TURN_LIVENESS_SECS": "10",
    "BUZZ_ACP_CONTEXT_MESSAGE_LIMIT": "30",
    "BUZZ_ACP_LAZY_POOL": "true",
    "BUZZ_ACP_IDLE_POOL_SLEEP": "1800",
}

PROMPT_TEMPLATE = """\
You are {description}, running on the host of {user} as that Unix user.
Workspace: {home}. Projects normally live in {home}/tmp and {home}/projects.
Answer only through Buzz (use the buzz CLI to reply in the channel/DM you were
asked in). Only the owner and the sibling agents are allowed to talk to you.
"""

UNIT_TEMPLATE = """\
[Unit]
Description=Buzz ACP {description} Agent
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User={user}
Group={group}
WorkingDirectory={home}
{environment}
EnvironmentFile={env_path}
{extra}
ExecStart={install_dir}/buzz-acp
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
"""


# ---- binaries --------------------------------------------------------------
def deb_data_tar(deb_path):
    """Bytes of the data.tar* member of a .deb (an ar archive)."""
    with open(deb_path, "rb") as f:
        if f.read(8) != b"!<arch>\n":
            fail("downloaded .deb is not a valid ar archive")
        while len(header := f.read(60)) == 60:
            name = header[:16].decode().strip().rstrip("/")
            size = int(header[48:58])
            data = f.read(size)
            f.read(size % 2)
            if name.startswith("data.tar"):
                return data
    fail("no data.tar member in .deb")


def install_binaries(force):
    """Install TARGET_BINARIES from the latest release unless already at that
    tag. Returns True if anything was installed."""
    req = urllib.request.Request(API_URL, headers={"Accept": "application/vnd.github+json"})
    with urllib.request.urlopen(req) as resp:
        release = json.load(resp)
    tag = release.get("tag_name")

    try:
        stamped = open(VERSION_STAMP).read().strip()
    except OSError:
        stamped = None
    present = all(os.path.isfile(os.path.join(INSTALL_DIR, b)) for b in TARGET_BINARIES)
    if not force and present and stamped == tag:
        print(f"already up to date ({tag}), nothing to do (use --force to reinstall)")
        return False

    url = next((a["browser_download_url"] for a in release.get("assets", [])
                if a.get("name", "").endswith("amd64.deb")), None)
    if not url:
        fail("no amd64 .deb asset found in latest release")

    with tempfile.NamedTemporaryFile(prefix="buzz-acp-") as deb:
        print(f"downloading {url} ...")
        with urllib.request.urlopen(url) as resp:
            shutil.copyfileobj(resp, deb)
        deb.flush()
        data = deb_data_tar(deb.name)

    with tarfile.open(fileobj=io.BytesIO(data), mode="r:*") as tf:
        members = {os.path.basename(m.name): m for m in tf.getmembers()
                   if m.isfile() and m.name.lstrip("./").startswith("usr/bin/")}
        for base in TARGET_BINARIES:
            if base not in members:
                fail(f"'{base}' not found in the .deb")
            fd, tmp = tempfile.mkstemp(dir=INSTALL_DIR, prefix=".tmp-")
            with os.fdopen(fd, "wb") as out:  # temp + rename: replaces busy binaries
                shutil.copyfileobj(tf.extractfile(members[base]), out)
            os.chmod(tmp, 0o755)
            os.replace(tmp, os.path.join(INSTALL_DIR, base))
            print(f"installed: {INSTALL_DIR}/{base}")

    write_if_changed(VERSION_STAMP, tag + "\n", 0o644, 0, 0)
    return True


# ---- config ----------------------------------------------------------------
def write_if_changed(path, content, mode, uid, gid):
    """Atomically write `content` only if it differs. True if (re)written."""
    try:
        if open(path).read() == content:
            print(f"unchanged: {path}")
            return False
    except OSError:
        pass
    fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".tmp-")
    with os.fdopen(fd, "w") as f:
        f.write(content)
    os.chmod(tmp, mode)
    os.chown(tmp, uid, gid)
    os.replace(tmp, path)
    print(f"written: {path}")
    return True


def systemctl(*cli_args):
    """Best-effort systemctl (non-fatal, e.g. no systemd in a container)."""
    try:
        subprocess.run(["systemctl", *cli_args], check=True, timeout=30)
    except (OSError, subprocess.SubprocessError) as e:
        print(f"warning: systemctl {' '.join(cli_args)} failed: {e}", file=sys.stderr)


def set_profile(label, priv, relay_url, name, about, uid, gid, home):
    """`buzz users set-profile` as the agent user with its own key (via env)."""
    http_url = relay_url.replace("wss://", "https://", 1).replace("ws://", "http://", 1)
    env = {"PATH": "/usr/local/bin:/usr/bin:/bin", "HOME": home,
           "BUZZ_PRIVATE_KEY": priv, "BUZZ_RELAY_URL": http_url}
    result = subprocess.run(
        [f"{INSTALL_DIR}/buzz", "users", "set-profile", "--name", name, "--about", about],
        env=env, user=uid, group=gid, cwd=home, capture_output=True, text=True, timeout=60)
    if result.returncode != 0:
        fail(f"set-profile for {label} failed: {(result.stderr or result.stdout).strip()}\n"
             "Is its pubkey added to the relay? Fix and re-run with --setup-profile.")
    print(f"profile set: {label} -> '{name}'")


def install_config(args, binaries_changed):
    """Keys, wrappers, prompts and systemd units for the agent user (root)."""
    if os.geteuid() != 0:
        fail("config setup requires root; rerun with sudo")
    try:
        pw = pwd.getpwnam(args.agent_user)
    except KeyError:
        fail(f"user '{args.agent_user}' does not exist")
    uid, gid, home = pw.pw_uid, pw.pw_gid, pw.pw_dir
    group = grp.getgrgid(gid).gr_name
    owner = to_hex(args.owner_pubkey or input("Owner pubkey (hex or npub): "), "npub")

    env_dir = os.path.join(home, ".buzz-acp")
    os.makedirs(env_dir, mode=0o700, exist_ok=True)
    os.chown(env_dir, uid, gid)
    os.chmod(env_dir, 0o700)

    active = {n: a for n, a in ACP_REGISTRY.items()
              if not getattr(args, "ignore_" + n.replace("-", "_"))}

    # Keys: reuse the key file; generate only with --setup-profile.
    keys, key_changed = {}, {}
    for name in active:
        env_path = os.path.join(env_dir, f"{name}.env")
        priv = read_key(env_path)
        if not priv:
            if not args.setup_profile:
                fail(f"no key for {name}; run with --setup-profile to generate one")
            priv = f"{secrets.randbelow(_N - 1) + 1:064x}"
        keys[name] = (priv, pubkey_from_private(priv), env_path)
        # Saved before any prompt so a generated key is never lost.
        key_changed[name] = write_if_changed(
            env_path, f'BUZZ_PRIVATE_KEY="{priv}"\n', 0o600, uid, gid)

    allowlist = ",".join(dict.fromkeys([owner] + [k[1] for k in keys.values()]))
    host = socket.gethostname()

    if args.setup_profile:
        print(f"\nAgent identities on {host} (add these pubkeys to the relay and channels):")
        for name, acp in active.items():
            pub = keys[name][1]
            print(f"  {acp['profile_name']}-{host}\n    hex:  {pub}\n"
                  f"    npub: {bech32_encode('npub', pub)}")
        if not args.yes:
            if not sys.stdin.isatty():
                fail("confirmation needed but stdin is not a terminal (pass --yes)")
            if input("\nPubkeys added to the relay? Set profiles and continue [y/N]: "
                     ).strip().lower() not in ("y", "yes"):
                fail("aborted; keys are saved, services untouched")
        for name, acp in active.items():
            set_profile(name, keys[name][0], args.buzz_relay_url,
                        f"{acp['profile_name']}-{host}",
                        f"{acp['description']} agent on {host} "
                        f"(owner {bech32_encode('npub', owner)})", uid, gid, home)

    changed_units = []
    for name, acp in active.items():
        env_path = keys[name][2]
        changed = binaries_changed or key_changed[name]
        changed |= write_if_changed(f"{INSTALL_DIR}/{acp['agent_command']}",
                                    "#!/bin/bash\n" + acp["wrapper"], 0o755, 0, 0)
        prompt_path = os.path.join(env_dir, f"{name}.prompt.md")
        changed |= write_if_changed(
            prompt_path, PROMPT_TEMPLATE.format(
                description=acp["description"], user=args.agent_user, home=home),
            0o644, uid, gid)

        env = {"BUZZ_RELAY_URL": args.buzz_relay_url, "BUZZ_ACP_AGENT_OWNER": owner,
               "BUZZ_ACP_AGENT_COMMAND": acp["agent_command"],
               "BUZZ_ACP_RESPOND_TO_ALLOWLIST": allowlist,
               "BUZZ_ACP_SESSION_TITLE": name, "BUZZ_ACP_SYSTEM_PROMPT_FILE": prompt_path,
               "PATH": "/usr/local/bin:/opt/node/bin:/usr/bin:/bin", "HOME": home,
               **COMMON_ENV, **acp["env"]}
        unit = UNIT_TEMPLATE.format(
            description=acp["description"], user=args.agent_user, group=group, home=home,
            environment="\n".join(f'Environment="{k}={v}"' for k, v in env.items()),
            env_path=env_path, extra="\n".join(acp["unit_lines"]), install_dir=INSTALL_DIR)
        unit_name = f"buzz-{name}.service"
        if write_if_changed(os.path.join(UNIT_DIR, unit_name), unit, 0o644, 0, 0):
            changed = True
        if changed:
            changed_units.append(unit_name)

    if changed_units:
        systemctl("daemon-reload")
    for unit_name in changed_units:
        if args.restart_service:
            systemctl("enable", "--now", unit_name)
            systemctl("restart", unit_name)
        else:
            print(f"apply with: sudo systemctl enable --now {unit_name} && "
                  f"sudo systemctl restart {unit_name}")

    print(f"setup complete. Allowlist (owner + agents): {allowlist}")
    print("Reminder: register each agent pubkey on the relay and add it to your channels.")


def build_arg_parser():
    p = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--agent-user", default=DEFAULT_AGENT_USER,
                   help=f"user to run the agents as (default: {DEFAULT_AGENT_USER})")
    p.add_argument("--owner-pubkey", help="your Nostr pubkey, hex or npub (prompted if omitted)")
    p.add_argument("--buzz-relay-url", help="e.g. wss://buzz.example.com (required)")
    p.add_argument("--setup-profile", action="store_true",
                   help="generate missing agent keys, wait for you to add them to the "
                        "relay, then set each agent's profile (<agent>-<hostname>)")
    p.add_argument("--yes", action="store_true", help="skip the --setup-profile prompt")
    p.add_argument("--restart-service", action="store_true",
                   help="enable and restart services whose config changed")
    p.add_argument("--force", action="store_true", help="reinstall binaries even if up to date")
    p.add_argument("--skip-config", action="store_true", help="only install binaries")
    for name in ACP_REGISTRY:
        p.add_argument(f"--ignore-{name}", action="store_true",
                       help=f"skip the {name} wrapper and service")
    return p


def main():
    args = build_arg_parser().parse_args()
    if platform.machine().lower() not in ("x86_64", "amd64") or sys.platform != "linux":
        fail("only linux amd64 is supported (upstream .deb)")
    if not args.skip_config and not args.buzz_relay_url:
        fail("--buzz-relay-url is required (or use --skip-config)")
    if os.geteuid() != 0 and not os.access(INSTALL_DIR, os.W_OK):
        fail(f"need write access to {INSTALL_DIR} (try sudo)")
    binaries_changed = install_binaries(args.force)
    if not args.skip_config:
        install_config(args, binaries_changed)


if __name__ == "__main__":
    main()
