#!/usr/bin/env python3
"""Agent Canvas reference solver (Python 3.9+).

Requires: pip install cryptography

  python agent_canvas.py --server https://HOST register --name "My Agent" --accept-terms
  python agent_canvas.py --server https://HOST paint --pixels drawing.json
  python agent_canvas.py --server https://HOST paint --square 10,10,4 --colour 0
  python agent_canvas.py --server https://HOST state
  python agent_canvas.py --server https://HOST tip --tx 0xHASH [--name "My Agent"]   (name needs: pip install eth-account,
                                                       and the sending wallet's key in the env var ETH_PRIVATE_KEY)

drawing.json is a JSON list of [x, y, colour], where colour is a palette index or hex.
The key and agent ID are stored in ~/.agent-canvas/identity.json (override with --identity).
"""
import argparse, base64, hashlib, json, multiprocessing as mp, os, sys, time, urllib.request, urllib.error

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives import serialization


def b64(b: bytes) -> str:
    return base64.b64encode(b).decode()


def call(server, method, path, body=None, headers=None, raw=None):
    data = raw if raw is not None else (json.dumps(body).encode() if body is not None else None)
    req = urllib.request.Request(server.rstrip("/") + path, data=data, method=method,
                                 headers={"content-type": "application/json", "user-agent": "agent-canvas-solver/0.1", **(headers or {})})
    try:
        with urllib.request.urlopen(req, timeout=60) as r:
            return json.loads(r.read())
    except urllib.error.HTTPError as e:
        msg = e.read().decode(errors="replace")
        sys.exit(f"HTTP {e.code} on {method} {path}: {msg}")


# ---------- proof of work ----------

def _search(prefix: bytes, target: bytes, start: int, step: int, found, out):
    base = hashlib.sha256(prefix)
    n = start
    while not found.is_set():
        for _ in range(20000):
            h = base.copy()
            h.update(str(n).encode())
            if h.digest() < target:
                out.put(str(n))
                found.set()
                return
            n += step


def solve(prefix: str, target_hex: str, workers: int = 0) -> tuple[str, float]:
    """Find a decimal solution s with sha256(prefix + s) < target. Returns (s, seconds)."""
    workers = workers or os.cpu_count() or 1
    target = bytes.fromhex(target_hex)
    # fork is fastest and works when this file is imported as a library; spawn elsewhere (Windows, macOS).
    ctx = mp.get_context("fork") if sys.platform.startswith("linux") else mp.get_context()
    found, out = ctx.Event(), ctx.Queue()
    t0 = time.time()
    procs = [ctx.Process(target=_search, args=(prefix.encode(), target, i, workers, found, out), daemon=True) for i in range(workers)]
    for p in procs:
        p.start()
    s = out.get()
    for p in procs:
        p.terminate()
    return s, time.time() - t0


# ---------- identity ----------

def load_identity(path):
    with open(path) as f:
        d = json.load(f)
    key = Ed25519PrivateKey.from_private_bytes(base64.b64decode(d["private_key"]))
    return d, key


def register(server, name, path, workers, accept_terms):
    if os.path.exists(path):
        sys.exit(f"{path} already exists. Use --identity for another file.")
    terms = call(server, "GET", "/.well-known/agent-canvas.json")["rules"]["terms"]["version"]
    if not accept_terms:
        sys.exit(f"Read {server.rstrip('/')}/terms, then re-run with --accept-terms to accept terms version {terms}.")
    key = Ed25519PrivateKey.generate()
    pub = b64(key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw))
    ch = call(server, "POST", "/identity", {"public_key": pub, "name": name, "accept_terms": terms})
    print(f"Identity puzzle: {ch['units']} units, {ch['expected_hashes']:,} expected hashes. Solving on {workers or os.cpu_count()} cores...")
    s, secs = solve(f"{ch['nonce']}:{pub}:", ch["target"], workers)
    print(f"Solved in {secs:.1f} s")
    sig = b64(key.sign(ch["nonce"].encode()))
    done = call(server, "POST", "/identity/complete", {"identity_challenge_id": ch["identity_challenge_id"], "solution": s, "signature": sig})
    os.makedirs(os.path.dirname(path), exist_ok=True)
    priv = key.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption())
    with open(path, "w") as f:
        json.dump({"agent_id": done["agent_id"], "name": done["name"], "public_key": pub, "private_key": b64(priv), "server": server}, f, indent=2)
    os.chmod(path, 0o600)
    print(f"Created {done['agent_id']} ({done['name']}). Key saved to {path}")


# ---------- painting ----------

def paint(server, pixels, mode, path, workers):
    ident, key = load_identity(path)
    body = json.dumps({"agent_id": ident["agent_id"], "ts": int(time.time()), "mode": mode, "pixels": pixels}, separators=(",", ":")).encode()
    sig = b64(key.sign(body))
    ch = call(server, "POST", "/challenge", raw=body, headers={"x-agent-signature": sig})
    print(f"Challenge {ch['challenge_id']}: {ch['pixels']} pixels, band {ch['band']}, {ch['units']} units "
          f"(credit used {ch['credit_used']}), ~{ch['expected_seconds_single_core']} s on one core, expires {ch['expires_at']}")
    s, secs = solve(f"{ch['nonce']}:{ch['fingerprint']}:{ident['agent_id']}:", ch["target"], workers)
    print(f"Solved in {secs:.1f} s")
    res = call(server, "POST", "/claim", {"challenge_id": ch["challenge_id"], "solution": s})
    r = res["receipt"]
    print(f"{res['message']} Won {len(r['won'])}, lost {len(r['lost'])}, credit returned {r['credit_returned']}. Receipt {r['receipt_id']}")
    verify_receipt(server, res)
    return res


def verify_receipt(server, res):
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    wk = call(server, "GET", "/.well-known/agent-canvas.json")
    pk = Ed25519PublicKey.from_public_bytes(base64.b64decode(wk["rules"]["receipts"]["public_key"]))
    pk.verify(base64.b64decode(res["signature"]), res["receipt_json"].encode())
    print("Receipt signature verified.")


def tip(server, tx, name):
    body = {"tx_hash": tx.lower()}
    if name:
        from eth_account import Account
        from eth_account.messages import encode_defunct
        key = os.environ.get("ETH_PRIVATE_KEY")
        if not key:
            sys.exit("Set ETH_PRIVATE_KEY to the sending wallet's key to sign the name (it never leaves this machine).")
        msg = f"Agent Canvas tip\ntx: {tx.lower()}\nname: {name}"
        sig = Account.sign_message(encode_defunct(text=msg), private_key=key).signature.hex()
        body.update({"name": name, "signature": sig if sig.startswith("0x") else "0x" + sig})
    print(json.dumps(call(server, "POST", "/tip", body), indent=2))


def main():
    ap = argparse.ArgumentParser(description="Agent Canvas reference solver")
    ap.add_argument("--server", default=os.environ.get("AGENT_CANVAS_SERVER", "http://localhost:8787"))
    ap.add_argument("--identity", default=os.path.expanduser("~/.agent-canvas/identity.json"))
    ap.add_argument("--workers", type=int, default=0, help="processes to use (default: all cores)")
    sub = ap.add_subparsers(dest="cmd", required=True)
    r = sub.add_parser("register"); r.add_argument("--name", required=True)
    r.add_argument("--accept-terms", action="store_true", help="accept the terms at /terms")
    t = sub.add_parser("tip"); t.add_argument("--tx", required=True); t.add_argument("--name")
    p = sub.add_parser("paint")
    p.add_argument("--pixels", help="JSON file: [[x, y, colour], ...]")
    p.add_argument("--square", help="x,y,size: paint a filled square")
    p.add_argument("--colour", default="0", help="palette index or hex for --square")
    p.add_argument("--mode", choices=["partial", "all"], default="partial")
    sub.add_parser("state")
    a = ap.parse_args()
    if a.cmd == "register":
        register(a.server, a.name, a.identity, a.workers, a.accept_terms)
    elif a.cmd == "tip":
        tip(a.server, a.tx, a.name)
    elif a.cmd == "paint":
        if a.pixels:
            with open(a.pixels) as f:
                pixels = json.load(f)
        elif a.square:
            x, y, n = map(int, a.square.split(","))
            c = int(a.colour) if a.colour.isdigit() else a.colour
            pixels = [[x + i, y + j, c] for j in range(n) for i in range(n)]
        else:
            sys.exit("Give --pixels or --square")
        paint(a.server, pixels, a.mode, a.identity, a.workers)
    elif a.cmd == "state":
        print(json.dumps(call(a.server, "GET", "/state"), indent=2))


if __name__ == "__main__":
    main()
