"""Tapwork SDK for Python: pay real people to answer your agent's questions (x402 on Robinhood Chain).

    import os
    from eth_account import Account
    from tapwork import ask
    r = ask("https://api.tapwork.lol", Account.from_key(os.environ["AGENT_KEY"]),
            "Which logo reads better at small size?", ["Ring", "Wordmark"], wait=60)
    r["result"]["answer"]   # "Ring"

Dependencies: eth-account (brings eth-abi and eth-utils). HTTP uses the standard library.
"""
from __future__ import annotations

import base64
import json
import re
import time
import urllib.error
import urllib.request

from eth_abi import encode
from eth_account import Account
from eth_account.messages import encode_typed_data
from eth_utils import keccak, to_checksum_address

SCHEME = "tapwork"
__all__ = ["ask", "build_payment", "task_hash", "task_id", "canonical_task", "wait_for_task", "sign_session", "sign_answer", "TapworkError"]

# JavaScript's \s, so the hash matches the server byte for byte
_JS_WS = "[\t\n\u000b\f\r    -     　﻿]"
_CTRL = re.compile("[\u0000-\u001f\u007f]")
_WS = re.compile(_JS_WS + "+")


class TapworkError(Exception):
    pass


def _clean(s) -> str:
    s = _CTRL.sub(" ", str("" if s is None else s))
    return _WS.sub(" ", s).strip("\t\n\u000b\f\r                  　﻿")


def _hex(b: bytes) -> str:
    return "0x" + b.hex()


def canonical_task(question: str, options: list, media: str | None = None) -> dict:
    return {"question": _clean(question), "options": [_clean(o) for o in options], "media": media or None}


def _hash_canonical(c: dict) -> str:
    s = json.dumps({"question": c["question"], "options": c["options"], "media": c["media"]}, ensure_ascii=False, separators=(",", ":"))
    return _hex(keccak(s.encode("utf-8")))


def task_hash(question: str, options: list, media: str | None = None) -> str:
    """keccak256(utf8(JSON.stringify({question, options, media}))) after collapsing whitespace."""
    return _hash_canonical(canonical_task(question, options, media))


def task_id(board: str, chain_id: int, agent: str, thash: str, reward: int, seats: int, deadline: int, salt: str) -> str:
    data = encode(
        ["address", "uint256", "address", "bytes32", "uint128", "uint8", "uint64", "bytes32"],
        [to_checksum_address(board), int(chain_id), to_checksum_address(agent), bytes.fromhex(thash[2:]), int(reward), int(seats), int(deadline), bytes.fromhex(salt[2:])],
    )
    return _hex(keccak(data))


_DOMAIN = [
    {"name": "name", "type": "string"},
    {"name": "version", "type": "string"},
    {"name": "chainId", "type": "uint256"},
    {"name": "verifyingContract", "type": "address"},
]


def typed_receive(domain: dict, message: dict) -> dict:
    return {
        "types": {
            "EIP712Domain": _DOMAIN,
            "ReceiveWithAuthorization": [
                {"name": "from", "type": "address"}, {"name": "to", "type": "address"}, {"name": "value", "type": "uint256"},
                {"name": "validAfter", "type": "uint256"}, {"name": "validBefore", "type": "uint256"}, {"name": "nonce", "type": "bytes32"},
            ],
        },
        "primaryType": "ReceiveWithAuthorization",
        "domain": domain,
        "message": message,
    }


def _same_url(a: str | None, b: str | None) -> bool:
    norm = lambda u: None if not u else re.sub(r"^([a-z]+://[^/]+)", lambda m: m.group(1).lower(), u.strip()).rstrip("/")
    return norm(a) == norm(b)


def build_payment(account, accept: dict, question: str, options: list, media: str | None = None, max_price: int | None = None, now: int | None = None) -> dict:
    """Sign the X-PAYMENT for a 402 accepts[0]. Refuses terms that are not for this question or cost too much."""
    if accept.get("scheme") != SCHEME:
        raise TapworkError("unsupported scheme " + str(accept.get("scheme")))
    x = accept["extra"]
    mine = canonical_task(question, options, media)
    theirs = x.get("task") or mine
    if theirs["question"] != mine["question"] or theirs["options"] != mine["options"] or not _same_url(theirs.get("media"), mine["media"]):
        raise TapworkError("server terms are for a different question")
    thash = _hash_canonical({**mine, "media": theirs.get("media")})
    if thash.lower() != x["taskHash"].lower():
        raise TapworkError("server terms are for a different question")
    if to_checksum_address(accept["payTo"]) != to_checksum_address(x["board"]):
        raise TapworkError("payTo must be the board")
    value = int(accept["maxAmountRequired"])
    if value != int(x["reward"]) + int(x["fee"]):
        raise TapworkError("price does not add up")
    if max_price is not None and value > int(max_price):
        raise TapworkError(f"price {value} is above your limit {max_price}")
    now = int(time.time()) if now is None else now
    agent = account.address
    tid = task_id(x["board"], x["chainId"], agent, thash, int(x["reward"]), int(x["seats"]), int(x["deadline"]), x["salt"])
    vb = min(int(x["deadline"]), now + 3600)
    domain = {"name": x["name"], "version": x["version"], "chainId": int(x["chainId"]), "verifyingContract": to_checksum_address(accept["asset"])}
    msg = {"from": agent, "to": to_checksum_address(x["board"]), "value": value, "validAfter": 0, "validBefore": vb, "nonce": bytes.fromhex(tid[2:])}
    sig = Account.sign_message(encode_typed_data(full_message=typed_receive(domain, msg)), account.key).signature
    sig_hex = sig.hex() if sig.hex().startswith("0x") else "0x" + sig.hex()
    payment = {
        "x402Version": 1, "scheme": SCHEME, "network": accept["network"],
        "payload": {
            "signature": sig_hex,
            "authorization": {"from": agent, "to": msg["to"], "value": str(value), "validAfter": "0", "validBefore": str(vb), "nonce": tid},
            "terms": {"taskHash": thash, "reward": str(x["reward"]), "seats": int(x["seats"]), "deadline": int(x["deadline"]), "salt": x["salt"]},
        },
    }
    return {"header": base64.b64encode(json.dumps(payment).encode()).decode(), "task_id": tid, "value": value}


def _post(url: str, body: dict, headers: dict | None = None, timeout: float = 150):
    req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST", headers={"content-type": "application/json", **(headers or {})})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.status, json.loads(r.read() or b"null")
    except urllib.error.HTTPError as e:
        return e.code, json.loads(e.read() or b"null")


def ask(api: str, account, question: str, options: list, media: str | None = None, seats: int | None = None, reward: int | None = None,
        seconds: int | None = None, wait: int | None = None, max_price: int | None = None) -> dict:
    """Ask people. Pays reward + fee in USDG from `account` (an eth_account LocalAccount on the agent's machine)."""
    body = {k: v for k, v in {"question": question, "options": options, "media": media, "seats": seats,
                              "reward": None if reward is None else str(reward), "seconds": seconds}.items() if v is not None}
    url = api.rstrip("/") + "/ask" + (f"?wait={int(wait)}" if wait else "")
    st, j = _post(url, body)
    if st != 402:
        raise TapworkError((j or {}).get("error") or f"expected 402, got {st}")
    pay = build_payment(account, j["accepts"][0], question, options, media, max_price)
    st, j = _post(url, body, {"x-payment": pay["header"]})
    if st == 402:
        raise TapworkError("payment not accepted: " + str((j or {}).get("error")))
    if st >= 300:
        raise TapworkError((j or {}).get("error") or f"ask failed with {st}")
    return j


def wait_for_task(api: str, tid: str, timeout: float = 120, every: float = 2) -> dict:
    t0 = time.time()
    while True:
        try:
            with urllib.request.urlopen(api.rstrip("/") + "/api/task/" + tid, timeout=20) as r:
                t = json.loads(r.read())
                if t.get("status") in ("settled", "refunded", "failed"):
                    return t
        except urllib.error.HTTPError:
            pass
        if time.time() - t0 > timeout:
            raise TapworkError("timeout waiting for task")
        time.sleep(every)


def _worker_domain(chain_id: int, board: str) -> dict:
    return {"name": "Tapwork", "version": "1", "chainId": int(chain_id), "verifyingContract": to_checksum_address(board)}


def sign_session(wallet, chain_id: int, board: str, key: str, expires: int) -> dict:
    typed = {"types": {"EIP712Domain": _DOMAIN, "Session": [{"name": "worker", "type": "address"}, {"name": "key", "type": "address"}, {"name": "expires", "type": "uint64"}]},
             "primaryType": "Session", "domain": _worker_domain(chain_id, board), "message": {"worker": wallet.address, "key": to_checksum_address(key), "expires": int(expires)}}
    sig = Account.sign_message(encode_typed_data(full_message=typed), wallet.key).signature.hex()
    return {"worker": wallet.address, "key": to_checksum_address(key), "expires": int(expires), "signature": sig if sig.startswith("0x") else "0x" + sig}


def sign_answer(key_account, chain_id: int, board: str, tid: str, choice: int) -> str:
    typed = {"types": {"EIP712Domain": _DOMAIN, "Answer": [{"name": "taskId", "type": "bytes32"}, {"name": "choice", "type": "uint8"}]},
             "primaryType": "Answer", "domain": _worker_domain(chain_id, board), "message": {"taskId": bytes.fromhex(tid[2:]), "choice": int(choice)}}
    sig = Account.sign_message(encode_typed_data(full_message=typed), key_account.key).signature.hex()
    return sig if sig.startswith("0x") else "0x" + sig
