#!/usr/bin/env python3
"""Minimal canvas client: paints one pixel, or an image with --image.

    pip install argon2-cffi          (and Pillow for --image)
    python3 client.py https://canvas.example 10 20 ff8800
    python3 client.py https://canvas.example --image logo.png 100 100
    NAME=yourname python3 client.py ...      (leaderboard name; a random one if unset)
"""
import json, os, random, struct, sys, urllib.request, urllib.error
from argon2.low_level import hash_secret_raw, Type

ADJ = ["brisk", "quiet", "neon", "lucky", "sly", "bold", "tiny", "rusty", "fuzzy", "swift", "odd", "calm"]
ANIMAL = ["otter", "fox", "moth", "heron", "lynx", "gecko", "crow", "newt", "yak", "owl", "eel", "wren"]
NAME = os.environ.get("NAME") or f"{random.choice(ADJ)}-{random.choice(ANIMAL)}-{random.randrange(100)}"

def get_json(url):
    with urllib.request.urlopen(url) as r:
        return json.load(r)

def solve(epoch, x, y, rgb, bits, kib):
    """A nonce whose Argon2id(t=1, m=kib, p=1, 32 bytes) of
    x u16le | y u16le | r g b | nonce u64le, salted with the epoch,
    starts with `bits` zero bits."""
    prefix = struct.pack("<HH", x, y) + rgb
    limit = 1 << (256 - bits)
    nonce = random.getrandbits(62)  # random start: a repeat paint must not find the same (used) solution
    while True:
        h = hash_secret_raw(prefix + struct.pack("<Q", nonce), epoch, time_cost=1, memory_cost=kib,
                            parallelism=1, hash_len=32, type=Type.ID)
        if int.from_bytes(h, "big") < limit:
            return nonce
        nonce += 1

def paint(base, x, y, color_hex, kib):
    rgb = bytes.fromhex(color_hex)
    for _ in range(5):
        c = get_json(f"{base}/api/challenge?x={x}&y={y}")
        nonce = solve(bytes.fromhex(c["epoch"]), x, y, rgb, c["bits"], kib)
        body = json.dumps({"x": x, "y": y, "color": color_hex, "epoch": c["epoch"], "nonce": nonce,
                           "name": NAME}).encode()
        req = urllib.request.Request(f"{base}/api/paint", body, {"Content-Type": "application/json"})
        try:
            with urllib.request.urlopen(req):
                return c["bits"]
        except urllib.error.HTTPError as e:
            if e.code != 409:  # 409 = epoch rotated or price went up: ask again
                raise
    raise RuntimeError("pixel too contested, gave up")

if __name__ == "__main__":
    base = sys.argv[1].rstrip("/")
    kib = get_json(f"{base}/api/config")["pow_kib"]
    print("painting as", NAME)
    if sys.argv[2] == "--image":
        from PIL import Image
        img = Image.open(sys.argv[3]).convert("RGB")
        ox, oy = int(sys.argv[4]), int(sys.argv[5])
        for (px, py) in ((i, j) for j in range(img.height) for i in range(img.width)):
            r, g, b = img.getpixel((px, py))
            bits = paint(base, ox + px, oy + py, f"{r:02x}{g:02x}{b:02x}", kib)
            print(f"({ox + px},{oy + py}) price {bits}")
    else:
        x, y, color = int(sys.argv[2]), int(sys.argv[3]), sys.argv[4]
        print("painted, price", paint(base, x, y, color, kib))
