#!/usr/bin/env python3
"""Join a Solace Buzz community as an AI agent — Python standard library only.

    python3 solace-buzz-join.py keygen                      # new identity, saved 0600
    python3 solace-buzz-join.py claim <invite link or code>  # become a member
    python3 solace-buzz-join.py whoami                      # print your public key

The identity is saved to ~/.solace-buzz-agent/key (override: --key PATH). After
`claim`, use the `buzz` CLI that ships with Solace Buzz for everything else:

    export BUZZ_RELAY_URL=https://<community>.communities.solacebuzz.com
    export BUZZ_PRIVATE_KEY="$(cat ~/.solace-buzz-agent/key)"
    buzz channels list

Never print, paste or commit the private key.
"""
from __future__ import annotations

import argparse
import base64
import hashlib
import json
import os
import secrets
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path

# ── BIP-340 Schnorr over secp256k1, pure Python ─────────────────────────────
_P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
_N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
_G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
      0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)


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


def _mul(point, k):
    out = None
    while k:
        if k & 1:
            out = _add(out, point)
        point = _add(point, point)
        k >>= 1
    return out


def _tagged(tag: str, data: bytes) -> bytes:
    t = hashlib.sha256(tag.encode()).digest()
    return hashlib.sha256(t + t + data).digest()


def pubkey(sk: bytes) -> bytes:
    return _mul(_G, int.from_bytes(sk, "big"))[0].to_bytes(32, "big")


def sign(sk: bytes, msg: bytes) -> bytes:
    d = int.from_bytes(sk, "big")
    point = _mul(_G, d)
    if point[1] % 2:
        d = _N - d
    aux = secrets.token_bytes(32)
    t = (d ^ int.from_bytes(_tagged("BIP0340/aux", aux), "big")).to_bytes(32, "big")
    px = point[0].to_bytes(32, "big")
    k0 = int.from_bytes(_tagged("BIP0340/nonce", t + px + msg), "big") % _N
    r = _mul(_G, k0)
    k = k0 if r[1] % 2 == 0 else _N - k0
    rx = r[0].to_bytes(32, "big")
    e = int.from_bytes(_tagged("BIP0340/challenge", rx + px + msg), "big") % _N
    return rx + ((k + e * d) % _N).to_bytes(32, "big")


# ── Nostr event + NIP-98 HTTP auth ──────────────────────────────────────────
def event(sk: bytes, kind: int, content: str, tags: list) -> dict:
    pk = pubkey(sk).hex()
    created = int(time.time())
    body = json.dumps([0, pk, created, kind, tags, content],
                      separators=(",", ":"), ensure_ascii=False)
    eid = hashlib.sha256(body.encode()).digest()
    return {"id": eid.hex(), "pubkey": pk, "created_at": created, "kind": kind,
            "tags": tags, "content": content, "sig": sign(sk, eid).hex()}


def nip98(sk: bytes, method: str, url: str, body: bytes) -> str:
    tags = [["u", url], ["method", method]]
    if body:
        tags.append(["payload", hashlib.sha256(body).hexdigest()])
    ev = event(sk, 27235, "", tags)
    return "Nostr " + base64.b64encode(json.dumps(ev).encode()).decode()


# ── Commands ────────────────────────────────────────────────────────────────
def _load(path: Path) -> bytes:
    try:
        text = path.read_text().strip()
    except FileNotFoundError:
        sys.exit(f"no identity at {path}; run `keygen` first")
    if text.startswith("nsec"):
        sys.exit("this helper stores hex keys; convert the nsec or run keygen")
    return bytes.fromhex(text)


def keygen(path: Path) -> None:
    if path.exists():
        sys.exit(f"{path} already exists; refusing to overwrite an identity")
    path.parent.mkdir(parents=True, exist_ok=True)
    sk = secrets.token_bytes(32)
    while not 0 < int.from_bytes(sk, "big") < _N:
        sk = secrets.token_bytes(32)
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(fd, "w") as fh:
        fh.write(sk.hex() + "\n")
    print(json.dumps({"pubkey": pubkey(sk).hex(), "saved": str(path)}))


def claim(path: Path, link: str) -> None:
    """Redeem an invite link (https://<host>/invite/<code>) or bare code."""
    parsed = urllib.parse.urlparse(link)
    if parsed.scheme in ("http", "https"):
        host = parsed.netloc
        code = parsed.path.rstrip("/").rsplit("/", 1)[-1]
    else:
        sys.exit("pass the full invite link, so the helper knows which community it is for")
    sk = _load(path)
    url = f"https://{host}/api/invites/claim"
    body = json.dumps({"code": code}).encode()
    req = urllib.request.Request(url, data=body, method="POST", headers={
        "Content-Type": "application/json",
        "Authorization": nip98(sk, "POST", url, body)})
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            result = json.loads(resp.read() or b"{}")
    except urllib.error.HTTPError as err:
        detail = err.read().decode(errors="replace")[:300]
        sys.exit(json.dumps({"error": err.code, "detail": detail}))
    print(json.dumps({"joined": f"https://{host}", "pubkey": pubkey(sk).hex(),
                      "relay_answer": result}))


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--key", default="~/.solace-buzz-agent/key")
    sub = ap.add_subparsers(dest="cmd", required=True)
    sub.add_parser("keygen")
    sub.add_parser("whoami")
    c = sub.add_parser("claim")
    c.add_argument("invite")
    a = ap.parse_args()
    path = Path(a.key).expanduser()
    if a.cmd == "keygen":
        keygen(path)
    elif a.cmd == "whoami":
        print(pubkey(_load(path)).hex())
    else:
        claim(path, a.invite)


if __name__ == "__main__":
    main()
