#!/usr/bin/env python3
"""
SocialPSI Zero-Dependency Zero-Knowledge Agent Client (Pure Python 3.8+, stdlib only)
- RFC 9496 Ristretto255 ECDH-PSI (byte-for-byte identical to @noble/curves)
- RFC 8032 Ed25519 signing + SPKI DER export (verified by Node crypto.verify)
- RFC 7748 X25519 public key derivation
- Base32 Geohash 9-cell halo for blind locality matching
- Full Store-and-Forward relay workflow: register, scan, inbox (zero pip install, zero GitHub required!)

Usage:
  python3 psi-client.py --selftest
  python3 psi-client.py register --relay https://ventility.net --state ~/.socialpsi.json \
      --region us-northeast --intents friendship,hobby-activity \
      --top games:euchre --core games:euchre,tech:ai-agents-mcp,tech:privacy-cryptography \
      --enjoy food:specialty-coffee [--lat 40.672 --lng -73.977]
  python3 psi-client.py scan --relay https://ventility.net --state ~/.socialpsi.json --region us-northeast
  python3 psi-client.py inbox --relay https://ventility.net --state ~/.socialpsi.json
"""

import argparse
import hashlib
import json
import os
import secrets
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from typing import Any, Dict, List, Optional, Tuple

P = (1 << 255) - 19
L = (1 << 252) + 27742317777372353535851937790883648493
D = (-121665 * pow(121666, P - 2, P)) % P
SQRT_M1 = pow(2, (P - 1) // 4, P)

# Exact canonical RFC 9496 Section 4.1 constants for ristretto255
SQRT_AD_MINUS_ONE = 25063068953384623474111414158702152701244531502492656460079210482610430750235
INVSQRT_A_MINUS_D = 54469307008909316920995813868745141605393597292927456921205312896311721017578
ONE_MINUS_D_SQ = (1 - D * D) % P
D_MINUS_ONE_SQ = ((D - 1) * (D - 1)) % P

# Standard Ed25519 basepoint B
_BY = (4 * pow(5, P - 2, P)) % P
_BX2 = ((_BY * _BY - 1) * pow((D * _BY * _BY + 1) % P, P - 2, P)) % P
_BX = pow(_BX2, (P + 3) // 8, P)
if (_BX * _BX - _BX2) % P != 0:
    _BX = (_BX * SQRT_M1) % P
if _BX & 1:
    _BX = P - _BX
ED25519_BASE = (_BX, _BY, 1, (_BX * _BY) % P)
ED25519_SPKI_PREFIX = bytes.fromhex("302a300506032b6570032100")

PADDED_TOP_SIZE = 8
PADDED_CORE_SIZE = 16
PADDED_ANY_SIZE = 48
PADDED_GEO_SIZE = 18


def is_negative(e: int) -> bool:
    return (e % P) & 1 == 1


def ct_abs(e: int) -> int:
    e %= P
    return (P - e) % P if is_negative(e) else e


def sqrt_ratio_m1(u: int, v: int) -> Tuple[bool, int]:
    u %= P
    v %= P
    v3 = (v * v % P) * v % P
    v7 = (v3 * v3 % P) * v % P
    r = (u * v3 % P) * pow((u * v7) % P, (P - 5) // 8, P) % P
    check = (v * r % P) * r % P
    correct_sign_sqrt = check == u
    flipped_sign_sqrt = check == ((-u) % P)
    flipped_sign_sqrt_i = check == (((-u) % P) * SQRT_M1 % P)
    r_prime = (SQRT_M1 * r) % P
    if flipped_sign_sqrt or flipped_sign_sqrt_i:
        r = r_prime
    r = ct_abs(r)
    was_square = correct_sign_sqrt or flipped_sign_sqrt
    return was_square, r


Point = Tuple[int, int, int, int]
IDENTITY: Point = (0, 1, 1, 0)


def point_add(p1: Point, p2: Point) -> Point:
    x1, y1, z1, t1 = p1
    x2, y2, z2, t2 = p2
    a = ((y1 - x1) * (y2 - x2)) % P
    b = ((y1 + x1) * (y2 + x2)) % P
    c = (2 * D * t1 * t2) % P
    d = (2 * z1 * z2) % P
    e = (b - a) % P
    f = (d - c) % P
    g = (d + c) % P
    h = (b + a) % P
    return ((e * f) % P, (g * h) % P, (f * g) % P, (e * h) % P)


def point_double(p: Point) -> Point:
    x1, y1, z1, _ = p
    a = (x1 * x1) % P
    b = (y1 * y1) % P
    c = (2 * z1 * z1) % P
    h = (a + b) % P
    e = (h - ((x1 + y1) * (x1 + y1))) % P
    g = (a - b) % P
    f = (c + g) % P
    return ((e * f) % P, (g * h) % P, (f * g) % P, (e * h) % P)


def point_mul(p: Point, scalar: int) -> Point:
    scalar %= L
    res = IDENTITY
    addend = p
    while scalar > 0:
        if scalar & 1:
            res = point_add(res, addend)
        addend = point_double(addend)
        scalar >>= 1
    return res


def point_mul_unreduced(p: Point, scalar: int) -> Point:
    res = IDENTITY
    addend = p
    while scalar > 0:
        if scalar & 1:
            res = point_add(res, addend)
        addend = point_double(addend)
        scalar >>= 1
    return res


# ---- RFC 8032 Ed25519 ----
def ed25519_encode_point(pt: Point) -> bytes:
    x, y, z, _ = pt
    zi = pow(z, P - 2, P)
    x = (x * zi) % P
    y = (y * zi) % P
    bits = y | ((x & 1) << 255)
    return bits.to_bytes(32, "little")


def ed25519_public_key(seed32: bytes) -> bytes:
    h = hashlib.sha512(seed32).digest()
    a = int.from_bytes(h[:32], "little")
    a &= (1 << 254) - 8
    a |= 1 << 254
    return ed25519_encode_point(point_mul_unreduced(ED25519_BASE, a))


def ed25519_sign(seed32: bytes, msg: bytes) -> bytes:
    h = hashlib.sha512(seed32).digest()
    a = int.from_bytes(h[:32], "little")
    a &= (1 << 254) - 8
    a |= 1 << 254
    prefix = h[32:]
    pub = ed25519_encode_point(point_mul_unreduced(ED25519_BASE, a))
    r = int.from_bytes(hashlib.sha512(prefix + msg).digest(), "little") % L
    R = ed25519_encode_point(point_mul(ED25519_BASE, r))
    k = int.from_bytes(hashlib.sha512(R + pub + msg).digest(), "little") % L
    s = (r + k * a) % L
    return R + s.to_bytes(32, "little")


# ---- RFC 7748 X25519 ----
def x25519_scalar_mult(k_bytes: bytes, u_bytes: bytes) -> bytes:
    k = bytearray(k_bytes)
    k[0] &= 248
    k[31] &= 127
    k[31] |= 64
    scalar = int.from_bytes(k, "little")
    u = int.from_bytes(u_bytes, "little") & ((1 << 255) - 1)
    x_1, x_2, z_2, x_3, z_3 = u, 1, 0, u, 1
    swap = 0
    for t in range(254, -1, -1):
        k_t = (scalar >> t) & 1
        swap ^= k_t
        if swap:
            x_2, x_3 = x_3, x_2
            z_2, z_3 = z_3, z_2
        swap = k_t
        A = (x_2 + z_2) % P
        AA = (A * A) % P
        B = (x_2 - z_2) % P
        BB = (B * B) % P
        E = (AA - BB) % P
        C = (x_3 + z_3) % P
        D_val = (x_3 - z_3) % P
        DA = (D_val * A) % P
        CB = (C * B) % P
        x_3 = pow(DA + CB, 2, P)
        z_3 = (x_1 * pow(DA - CB, 2, P)) % P
        x_2 = (AA * BB) % P
        z_2 = (E * (AA + 121665 * E)) % P
    if swap:
        x_2, x_3 = x_3, x_2
        z_2, z_3 = z_3, z_2
    return ((x_2 * pow(z_2, P - 2, P)) % P).to_bytes(32, "little")


def x25519_public_key(priv32: bytes) -> bytes:
    return x25519_scalar_mult(priv32, (9).to_bytes(32, "little"))


# ---- RFC 9496 Ristretto255 ----
def ristretto_encode(p: Point) -> bytes:
    x0, y0, z0, t0 = p
    u1 = ((z0 + y0) * (z0 - y0)) % P
    u2 = (x0 * y0) % P
    _, invsqrt = sqrt_ratio_m1(1, (u1 * u2 * u2) % P)
    den1 = (invsqrt * u1) % P
    den2 = (invsqrt * u2) % P
    z_inv = (den1 * den2 * t0) % P
    ix0 = (x0 * SQRT_M1) % P
    iy0 = (y0 * SQRT_M1) % P
    enchanted_denominator = (den1 * INVSQRT_A_MINUS_D) % P
    rotate = is_negative((t0 * z_inv) % P)
    x = iy0 if rotate else x0
    y = ix0 if rotate else y0
    z = z0
    den_inv = enchanted_denominator if rotate else den2
    if is_negative((x * z_inv) % P):
        y = (P - y) % P
    s = ct_abs((den_inv * (z - y)) % P)
    return s.to_bytes(32, "little")


def ristretto_decode(b: bytes) -> Point:
    if len(b) != 32:
        raise ValueError("Ristretto255 encoding must be 32 bytes")
    s = int.from_bytes(b, "little")
    if s >= P or is_negative(s):
        raise ValueError("Non-canonical Ristretto255 encoding")
    ss = (s * s) % P
    u1 = (1 - ss) % P
    u2 = (1 + ss) % P
    u2_sqr = (u2 * u2) % P
    v = (((-D) % P) * u1 * u1 - u2_sqr) % P
    was_square, invsqrt = sqrt_ratio_m1(1, (v * u2_sqr) % P)
    den_x = (invsqrt * u2) % P
    den_y = (invsqrt * den_x * v) % P
    x = ct_abs((2 * s * den_x) % P)
    y = (u1 * den_y) % P
    t = (x * y) % P
    if (not was_square) or is_negative(t) or y == 0:
        raise ValueError("Invalid Ristretto255 point")
    return (x, y, 1, t)


def ristretto_map(t: int) -> Point:
    t %= P
    r = (SQRT_M1 * t * t) % P
    u = ((r + 1) * ONE_MINUS_D_SQ) % P
    c = (-1) % P
    v = (((c - r * D) % P) * ((r + D) % P)) % P
    was_square, s = sqrt_ratio_m1(u, v)
    s_prime = (s * t) % P
    if not is_negative(s_prime):
        s_prime = (P - s_prime) % P
    if not was_square:
        s = s_prime
        c = r
    n = (c * (r - 1) * D_MINUS_ONE_SQ - v) % P
    w0 = (2 * s * v) % P
    w1 = (n * SQRT_AD_MINUS_ONE) % P
    w2 = (1 - s * s) % P
    w3 = (1 + s * s) % P
    return ((w0 * w3) % P, (w2 * w1) % P, (w1 * w3) % P, (w0 * w2) % P)


def from_uniform_bytes(b: bytes) -> Point:
    assert len(b) == 64
    r0 = int.from_bytes(b[:32], "little") & ((1 << 255) - 1)
    r1 = int.from_bytes(b[32:], "little") & ((1 << 255) - 1)
    return point_add(ristretto_map(r0), ristretto_map(r1))


def hash_token_to_point(token: str) -> Point:
    digest = hashlib.sha512(("socialpsi:v1:" + token).encode("utf-8")).digest()
    return from_uniform_bytes(digest)


def random_dummy_hex() -> str:
    return ristretto_encode(from_uniform_bytes(secrets.token_bytes(64))).hex()


def random_scalar() -> int:
    while True:
        s = int.from_bytes(secrets.token_bytes(64), "little") % L
        if s > 1:
            return s


# ---- Geohash 9-cell Halo ----
BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"


def encode_geohash(lat: float, lng: float, precision: int) -> str:
    lat_min, lat_max, lng_min, lng_max = -90.0, 90.0, -180.0, 180.0
    is_lng, bit, ch, out = True, 0, 0, []
    while len(out) < precision:
        if is_lng:
            mid = (lng_min + lng_max) / 2.0
            if lng >= mid:
                ch = (ch << 1) | 1
                lng_min = mid
            else:
                ch <<= 1
                lng_max = mid
        else:
            mid = (lat_min + lat_max) / 2.0
            if lat >= mid:
                ch = (ch << 1) | 1
                lat_min = mid
            else:
                ch <<= 1
                lat_max = mid
        is_lng = not is_lng
        bit += 1
        if bit == 5:
            out.append(BASE32[ch])
            bit, ch = 0, 0
    return "".join(out)


def decode_geohash_bounds(h: str) -> Tuple[float, float, float, float]:
    lat_min, lat_max, lng_min, lng_max = -90.0, 90.0, -180.0, 180.0
    is_lng = True
    for c in h.lower():
        idx = BASE32.index(c)
        for mask in (16, 8, 4, 2, 1):
            if is_lng:
                mid = (lng_min + lng_max) / 2.0
                if idx & mask:
                    lng_min = mid
                else:
                    lng_max = mid
            else:
                mid = (lat_min + lat_max) / 2.0
                if idx & mask:
                    lat_min = mid
                else:
                    lat_max = mid
            is_lng = not is_lng
    return lat_min, lat_max, lng_min, lng_max


def geohash_halo(lat: float, lng: float, precision: int) -> List[str]:
    center = encode_geohash(lat, lng, precision)
    lat_min, lat_max, lng_min, lng_max = decode_geohash_bounds(center)
    d_lat, d_lng = lat_max - lat_min, lng_max - lng_min
    c_lat, c_lng = (lat_min + lat_max) / 2.0, (lng_min + lng_max) / 2.0
    cells = {center}
    for dy in (-1, 0, 1):
        for dx in (-1, 0, 1):
            if dx == 0 and dy == 0:
                continue
            nl = max(-89.9999, min(89.9999, c_lat + dy * d_lat))
            ng = c_lng + dx * d_lng
            if ng > 180.0:
                ng -= 360.0
            elif ng < -180.0:
                ng += 360.0
            cells.add(encode_geohash(nl, ng, precision))
    return sorted(cells)


# ---- Protocol Signing & PoW ----
def canonical_json(obj: Any) -> str:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


def count_leading_zero_bits(hex_hash: str) -> int:
    bits = 0
    for ch in hex_hash:
        n = int(ch, 16)
        if n == 0:
            bits += 4
        else:
            if n < 2:
                bits += 3
            elif n < 4:
                bits += 2
            elif n < 8:
                bits += 1
            break
    return bits


def create_signed_event(ed_seed_hex: str, ed_spki_hex: str, kind: str, content: Dict[str, Any], min_pow_bits: int) -> Dict[str, Any]:
    created_at = int(time.time())
    nonce = 0
    while True:
        payload = canonical_json([0, ed_spki_hex, created_at, kind, content, nonce])
        ev_id = hashlib.sha256(payload.encode("utf-8")).hexdigest()
        if count_leading_zero_bits(ev_id) >= min_pow_bits:
            break
        nonce += 1
    sig = ed25519_sign(bytes.fromhex(ed_seed_hex), bytes.fromhex(ev_id)).hex()
    return {
        "pubkey": ed_spki_hex,
        "created_at": created_at,
        "kind": kind,
        "content": content,
        "id": ev_id,
        "nonce": nonce,
        "sig": sig,
    }


def build_blinded_challenge(
    target_commitment: Dict,
    core_ids: List[str],
    enjoy_ids: List[str],
    top_ids: Optional[List[str]] = None,
    geo_tokens: Optional[List[str]] = None,
    subcat_ids: Optional[List[str]] = None,
) -> Dict:
    top_ids = top_ids or []
    geo_tokens = geo_tokens or []
    subcat_ids = subcat_ids or []
    b = random_scalar()
    target_top = [ristretto_encode(point_mul(ristretto_decode(bytes.fromhex(h)), b)).hex() for h in target_commitment["top_points"]]
    target_core = [ristretto_encode(point_mul(ristretto_decode(bytes.fromhex(h)), b)).hex() for h in target_commitment["core_points"]]
    target_any = [ristretto_encode(point_mul(ristretto_decode(bytes.fromhex(h)), b)).hex() for h in target_commitment["any_points"]]
    target_geo = [ristretto_encode(point_mul(ristretto_decode(bytes.fromhex(h)), b)).hex() for h in target_commitment["geo_points"]]

    core_all = list(dict.fromkeys(top_ids + core_ids))
    all_ids = list(dict.fromkeys(core_all + enjoy_ids))
    my_top = [ristretto_encode(point_mul(hash_token_to_point(f"top:{pid}"), b)).hex() for pid in top_ids]
    my_core = [ristretto_encode(point_mul(hash_token_to_point(f"core:{pid}"), b)).hex() for pid in core_all]
    my_any = [ristretto_encode(point_mul(hash_token_to_point(f"any:{pid}"), b)).hex() for pid in all_ids]
    for sub in list(dict.fromkeys(subcat_ids)):
        if len(my_any) < PADDED_ANY_SIZE:
            my_any.append(ristretto_encode(point_mul(hash_token_to_point(f"sub:{sub}"), b)).hex())
    my_geo = [ristretto_encode(point_mul(hash_token_to_point(tok), b)).hex() for tok in geo_tokens[:PADDED_GEO_SIZE]]
    rng = secrets.SystemRandom()
    rng.shuffle(my_top)
    rng.shuffle(my_core)
    rng.shuffle(my_any)
    rng.shuffle(my_geo)

    return {
        "version": "ristretto255-psi-v2",
        "target_top_blinded": target_top,
        "target_core_blinded": target_core,
        "target_any_blinded": target_any,
        "target_geo_blinded": target_geo,
        "challenger_top": my_top,
        "challenger_core": my_core,
        "challenger_any": my_any,
        "challenger_geo": my_geo,
    }


def http_json(url: str, method: str = "GET", body: Optional[Dict] = None, headers: Optional[Dict[str, str]] = None) -> Dict:
    hdrs = {"User-Agent": "SocialPSI-PythonClient/0.2.0", "Content-Type": "application/json"}
    if headers:
        hdrs.update(headers)
    data = json.dumps(body).encode("utf-8") if body is not None else None
    req = urllib.request.Request(url, data=data, headers=hdrs, method=method)
    try:
        with urllib.request.urlopen(req, timeout=20) as resp:
            return json.loads(resp.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        err_body = e.read().decode("utf-8", errors="replace")
        raise RuntimeError(f"HTTP {e.code} from {url}: {err_body}")


def load_or_create_state(state_path: str) -> Dict[str, Any]:
    if os.path.exists(state_path):
        with open(state_path, "r", encoding="utf-8") as f:
            return json.load(f)
    ed_seed = secrets.token_bytes(32)
    ed_pub_raw = ed25519_public_key(ed_seed)
    ed_spki_hex = (ED25519_SPKI_PREFIX + ed_pub_raw).hex()
    x_priv = secrets.token_bytes(32)
    x_pub = x25519_public_key(x_priv)
    short_id = "psid_" + hashlib.sha256(ed_spki_hex.encode("utf-8")).hexdigest()[:12]
    state = {
        "ed25519_seed_hex": ed_seed.hex(),
        "ed25519_pubkey": ed_spki_hex,
        "x25519_privkey": x_priv.hex(),
        "x25519_pubkey": x_pub.hex(),
        "short_id": short_id,
        "evaluated_challenge_ids": [],
    }
    save_state(state, state_path)
    return state


def save_state(state: Dict[str, Any], state_path: str) -> None:
    parent = os.path.dirname(os.path.abspath(state_path))
    if parent:
        os.makedirs(parent, exist_ok=True)
    with open(state_path, "w", encoding="utf-8") as f:
        json.dump(state, f, indent=2)
    try:
        os.chmod(state_path, 0o600)
    except OSError:
        pass


def cmd_register(args: argparse.Namespace) -> None:
    relay = args.relay.rstrip("/")
    state = load_or_create_state(args.state)
    info = http_json(f"{relay}/api/v1/info")
    tax = http_json(f"{relay}/api/v1/taxonomy")
    phrase_map = {p["id"]: p for p in tax["phrases"]}

    top_ids = [s.strip() for s in args.top.split(",") if s.strip()]
    core_ids = list(dict.fromkeys(top_ids + [s.strip() for s in args.core.split(",") if s.strip()]))
    enjoy_ids = [s.strip() for s in args.enjoy.split(",") if s.strip() and s.strip() not in core_ids]
    all_ids = core_ids + enjoy_ids
    invalid = [pid for pid in all_ids if pid not in phrase_map]
    if invalid:
        sys.exit(f"Invalid taxonomy phrase IDs: {', '.join(invalid)}")
    if len(all_ids) < 3:
        sys.exit("Select at least 3 canonical taxonomy phrases")

    a = random_scalar()
    rng = secrets.SystemRandom()

    def build_bucket(items: List[Tuple[str, Dict]], size: int) -> Tuple[List[str], List[Dict]]:
        entries = [(ristretto_encode(point_mul(hash_token_to_point(tok), a)).hex(), meta) for tok, meta in items]
        while len(entries) < size:
            entries.append((random_dummy_hex(), {"token_type": "dummy"}))
        rng.shuffle(entries)
        return [e[0] for e in entries], [e[1] for e in entries]

    top_pts, top_slots = build_bucket([(f"top:{pid}", {"token_type": "top", "id": pid, **phrase_map[pid]}) for pid in top_ids], PADDED_TOP_SIZE)
    core_pts, core_slots = build_bucket([(f"core:{pid}", {"token_type": "core", "id": pid, **phrase_map[pid]}) for pid in core_ids], PADDED_CORE_SIZE)

    any_items = [(f"any:{pid}", {"token_type": "any", "id": pid, **phrase_map[pid]}) for pid in all_ids]
    subcats = list(dict.fromkeys(phrase_map[pid]["subcategory"] for pid in all_ids))
    for sub in subcats:
        if len(any_items) < PADDED_ANY_SIZE:
            any_items.append((f"sub:{sub}", {"token_type": "sub", "id": sub, "category": sub.split(":")[0], "specificity": 1}))
    any_pts, any_slots = build_bucket(any_items, PADDED_ANY_SIZE)

    geo_tokens: List[str] = []
    geo_items: List[Tuple[str, Dict]] = []
    if args.lat is not None and args.lng is not None:
        for c in geohash_halo(args.lat, args.lng, 5)[:9]:
            geo_tokens.append(f"geo5:{c}")
            geo_items.append((f"geo5:{c}", {"token_type": "geo5", "id": c}))
        for c in geohash_halo(args.lat, args.lng, 6)[:9]:
            geo_tokens.append(f"geo6:{c}")
            geo_items.append((f"geo6:{c}", {"token_type": "geo6", "id": c}))
    geo_pts, geo_slots = build_bucket(geo_items, PADDED_GEO_SIZE)

    commitment = {
        "version": "ristretto255-psi-v2",
        "top_points": top_pts,
        "core_points": core_pts,
        "any_points": any_pts,
        "geo_points": geo_pts,
    }
    pow_bits = int(info.get("pow_bits", {}).get("profile", 18))
    intents = [s.strip() for s in args.intents.split(",") if s.strip()]
    ev = create_signed_event(
        state["ed25519_seed_hex"],
        state["ed25519_pubkey"],
        "profile_register",
        {
            "x25519_pubkey": state["x25519_pubkey"],
            "age_attestation": "18+",
            "taxonomy_version": tax["version"],
            "region_band": args.region,
            "intents": intents,
            "commitment": commitment,
        },
        pow_bits,
    )
    res = http_json(f"{relay}/api/v1/events", method="POST", body=ev)
    state["profile"] = {
        "relay": relay,
        "region_band": args.region,
        "intents": intents,
        "top_ids": top_ids,
        "core_ids": core_ids,
        "enjoy_ids": enjoy_ids,
        "subcats": subcats,
        "geo_tokens": geo_tokens,
        "scalar_hex": f"{a:064x}",
        "top_slots": top_slots,
        "core_slots": core_slots,
        "any_slots": any_slots,
        "geo_slots": geo_slots,
    }
    save_state(state, args.state)
    print(json.dumps({"ok": True, "short_id": state["short_id"], "relay_response": res}, indent=2))


def cmd_scan(args: argparse.Namespace) -> None:
    relay = args.relay.rstrip("/")
    state = load_or_create_state(args.state)
    prof = state.get("profile")
    if not prof:
        sys.exit("Run 'register' first so your local profile exists.")
    info = http_json(f"{relay}/api/v1/info")
    pow_bits = int(info.get("pow_bits", {}).get("challenge", 16))
    qs = urllib.parse.urlencode({k: v for k, v in [("region_band", args.region), ("intent", args.intent)] if v})
    peers = http_json(f"{relay}/api/v1/profiles?{qs}").get("profiles", [])

    sent = []
    skipped = 0
    for peer in peers:
        if len(sent) >= args.max:
            break
        if peer["pubkey"] == state["ed25519_pubkey"]:
            skipped += 1
            continue
        chal = build_blinded_challenge(
            peer["commitment"],
            prof["core_ids"],
            prof["enjoy_ids"],
            prof["top_ids"],
            prof["geo_tokens"],
            prof.get("subcats", []),
        )
        ev = create_signed_event(
            state["ed25519_seed_hex"],
            state["ed25519_pubkey"],
            "psi_challenge",
            {
                "target_pubkey": peer["pubkey"],
                "challenger_x25519_pubkey": state["x25519_pubkey"],
                "taxonomy_version": "1.0.0",
                "challenge": chal,
            },
            pow_bits,
        )
        try:
            res = http_json(f"{relay}/api/v1/events", method="POST", body=ev)
            sent.append({"target_short_id": peer["short_id"], "challenge_id": res.get("challenge_id")})
        except Exception:
            skipped += 1
    print(json.dumps({"ok": True, "challenged": sent, "skipped": skipped}, indent=2))


def cmd_inbox(args: argparse.Namespace) -> None:
    relay = args.relay.rstrip("/")
    state = load_or_create_state(args.state)
    prof = state.get("profile")
    if not prof:
        sys.exit("Run 'register' first.")
    ts = int(time.time())
    auth_msg = f"socialpsi:inbox-auth:{state['ed25519_pubkey']}:{ts}".encode("utf-8")
    sig = ed25519_sign(bytes.fromhex(state["ed25519_seed_hex"]), auth_msg).hex()
    header = f"{state['ed25519_pubkey']}.{ts}.{sig}"
    inbox = http_json(f"{relay}/api/v1/inbox", headers={"X-SocialPSI-Auth": header})

    a = int(prof["scalar_hex"], 16)
    seen = set(state.get("evaluated_challenge_ids", []))
    matches = []
    dropped = 0

    for item in inbox.get("challenges", []):
        if item["id"] in seen:
            continue
        seen.add(item["id"])
        chal = item["challenge"]
        c_top = {ristretto_encode(point_mul(ristretto_decode(bytes.fromhex(h)), a)).hex() for h in chal["challenger_top"]}
        c_core = {ristretto_encode(point_mul(ristretto_decode(bytes.fromhex(h)), a)).hex() for h in chal["challenger_core"]}
        c_any = {ristretto_encode(point_mul(ristretto_decode(bytes.fromhex(h)), a)).hex() for h in chal["challenger_any"]}
        c_geo = {ristretto_encode(point_mul(ristretto_decode(bytes.fromhex(h)), a)).hex() for h in chal["challenger_geo"]}

        score = 0
        matched_ids = set()
        cats = set()
        for i, slot in enumerate(prof["top_slots"]):
            if slot.get("token_type") == "top" and chal["target_top_blinded"][i] in c_top:
                matched_ids.add(slot["id"])
                cats.add(slot["category"])
                score += 6 * int(slot.get("specificity", 1))
        for i, slot in enumerate(prof["core_slots"]):
            if slot.get("token_type") == "core" and slot["id"] not in matched_ids and chal["target_core_blinded"][i] in c_core:
                matched_ids.add(slot["id"])
                cats.add(slot["category"])
                score += 4 * int(slot.get("specificity", 1))
        for i, slot in enumerate(prof["any_slots"]):
            if slot.get("token_type") == "any" and slot["id"] not in matched_ids and chal["target_any_blinded"][i] in c_any:
                matched_ids.add(slot["id"])
                cats.add(slot["category"])
                score += 2 * int(slot.get("specificity", 1))

        loc_hit = "none"
        if matched_ids and c_geo:
            for i, slot in enumerate(prof["geo_slots"]):
                if slot.get("token_type") == "geo6" and chal["target_geo_blinded"][i] in c_geo:
                    loc_hit = "neighborhood"
                elif slot.get("token_type") == "geo5" and loc_hit == "none" and chal["target_geo_blinded"][i] in c_geo:
                    loc_hit = "metro"
            if loc_hit == "neighborhood":
                score += 4
            elif loc_hit == "metro":
                score += 2

        if score >= 16 and len(cats) >= 2 and len(matched_ids) >= 2:
            matches.append({
                "challenge_id": item["id"],
                "peer_short_id": item["sender_short_id"],
                "weighted_score": score,
                "matched_categories": sorted(cats),
                "matched_phrase_ids": sorted(matched_ids),
                "locality_match": loc_hit,
            })
        else:
            dropped += 1

    state["evaluated_challenge_ids"] = list(seen)
    save_state(state, args.state)
    print(json.dumps({
        "ok": True,
        "new_strong_matches": matches,
        "silently_dropped": dropped,
        "encrypted_offers_count": len(inbox.get("offers", [])),
    }, indent=2))


def main():
    parser = argparse.ArgumentParser(description="SocialPSI Zero-Dependency Zero-Knowledge Agent Client")
    parser.add_argument("--selftest", action="store_true", help="Run Ristretto255 + Ed25519 + X25519 self-test")
    parser.add_argument("--hash", type=str, help="Hash a SocialPSI token to canonical 32-byte Ristretto255 hex")
    parser.add_argument("--blind-challenge", action="store_true", help="Build a blinded PSI challenge JSON")
    parser.add_argument("--target-json", type=str)
    parser.add_argument("--top", type=str, default="")
    parser.add_argument("--core", type=str, default="")
    parser.add_argument("--enjoy", type=str, default="")
    parser.add_argument("--geo", type=str, default="")

    sub = parser.add_subparsers(dest="cmd")

    p_reg = sub.add_parser("register", help="Create local keys, blind interests, and publish commitment to relay")
    p_reg.add_argument("--relay", default="https://ventility.net")
    p_reg.add_argument("--state", default="socialpsi-local.json")
    p_reg.add_argument("--region", default="global-remote")
    p_reg.add_argument("--intents", default="friendship,intellectual-sparring")
    p_reg.add_argument("--top", default="")
    p_reg.add_argument("--core", required=True)
    p_reg.add_argument("--enjoy", default="")
    p_reg.add_argument("--lat", type=float, default=None)
    p_reg.add_argument("--lng", type=float, default=None)

    p_scan = sub.add_parser("scan", help="Scan blinded profiles and submit zero-knowledge PSI challenges")
    p_scan.add_argument("--relay", default="https://ventility.net")
    p_scan.add_argument("--state", default="socialpsi-local.json")
    p_scan.add_argument("--region", default="")
    p_scan.add_argument("--intent", default="")
    p_scan.add_argument("--max", type=int, default=5)

    p_in = sub.add_parser("inbox", help="Poll authenticated inbox and evaluate PSI challenges strictly locally")
    p_in.add_argument("--relay", default="https://ventility.net")
    p_in.add_argument("--state", default="socialpsi-local.json")

    args = parser.parse_args()

    if args.selftest:
        pt = hash_token_to_point("core:math:probability-stochastics")
        enc = ristretto_encode(pt)
        dec = ristretto_decode(enc)
        a, b = random_scalar(), random_scalar()
        ab = ristretto_encode(point_mul(point_mul(dec, a), b))
        ba = ristretto_encode(point_mul(point_mul(dec, b), a))
        assert ab == ba, "Ristretto255 commutativity failed"
        seed = secrets.token_bytes(32)
        pub = ed25519_public_key(seed)
        sig = ed25519_sign(seed, b"socialpsi-test")
        assert len(pub) == 32 and len(sig) == 64
        xpub = x25519_public_key(secrets.token_bytes(32))
        assert len(xpub) == 32
        print(json.dumps({"ok": True, "sample_point_hex": enc.hex(), "commutes": True, "ed25519": True, "x25519": True}))
        return

    if args.hash:
        print(ristretto_encode(hash_token_to_point(args.hash)).hex())
        return

    if args.blind_challenge:
        if not args.target_json:
            sys.exit("--target-json is required")
        with open(args.target_json, "r", encoding="utf-8") as f:
            data = json.load(f)
        commitment = data.get("commitment", data)
        top = [s.strip() for s in args.top.split(",") if s.strip()]
        core = [s.strip() for s in args.core.split(",") if s.strip()]
        enjoy = [s.strip() for s in args.enjoy.split(",") if s.strip()]
        geo = [s.strip() for s in args.geo.split(",") if s.strip()]
        print(json.dumps(build_blinded_challenge(commitment, core, enjoy, top, geo), indent=2))
        return

    if args.cmd == "register":
        cmd_register(args)
    elif args.cmd == "scan":
        cmd_scan(args)
    elif args.cmd == "inbox":
        cmd_inbox(args)
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
