"""SPILVON integration sample for Python 3.9+ (standard library only; Ed25519 needs `cryptography`).

    python3 spilvon.py wallet                  start the wallet API on :8080 (SPILVON calls it)
    python3 spilvon.py launch <player> <game>  create a session and print the launch URL

Environment: SPILVON_URL, SPILVON_OPERATOR, SPILVON_API_SECRET, SPILVON_WALLET_SECRET,
optional SPILVON_ED25519_PUBLIC_KEYS = JSON {"kid": "<base64 raw public key>"},
SPILVON_SAMPLE_TOKENS = JSON {"<casino session token>": "<player id>"} (live sessions the demo wallet accepts bets for).

Balances live in memory to keep the sample short. In production every handler is ONE database
transaction with a UNIQUE constraint on transaction_id (see the PRODUCTION comments).
"""
import base64, hashlib, hmac, json, os, sys, threading, time, urllib.request, urllib.error
from decimal import Decimal
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

SKEW_MS = 300_000
DECIMALS = {"USD": 2, "EUR": 2, "TRY": 2, "USDT": 6, "USDC": 6, "TRX": 6, "BTC": 8, "ETH": 8, "LTC": 8, "SOL": 8, "DOGE": 8}
env = lambda k: os.environ.get(k, "")


def signing_string(ts: str, method: str, path_and_query: str, body: str) -> str:
    return f"{ts}.{method.upper()}.{path_and_query}.{body}"


def hmac_hex(secret: str, s: str) -> str:
    return hmac.new(secret.encode(), s.encode("utf-8"), hashlib.sha256).hexdigest()


# ---- verification of SPILVON's calls ------------------------------------------------------
ED_KEYS = json.loads(env("SPILVON_ED25519_PUBLIC_KEYS") or "{}")


def verify_spilvon(headers, method: str, path_and_query: str, raw_body: str) -> bool:
    ts = headers.get("X-Spilvon-Timestamp", "")
    if headers.get("X-Spilvon-Operator") != env("SPILVON_OPERATOR") or not (ts.isdigit() and len(ts) == 13):
        return False
    if abs(time.time() * 1000 - int(ts)) > SKEW_MS:
        return False
    s = signing_string(ts, method, path_and_query, raw_body)
    ed_sig = headers.get("X-Spilvon-Signature-Ed25519")
    if ed_sig and ED_KEYS:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        from cryptography.exceptions import InvalidSignature
        raw_key = ED_KEYS.get(headers.get("X-Spilvon-Key-Id", ""))
        if not raw_key:  # unknown kid: refetch /.well-known/spilvon-wallet-keys.json once, then reject
            return False
        try:
            Ed25519PublicKey.from_public_bytes(base64.b64decode(raw_key)).verify(base64.b64decode(ed_sig), s.encode("utf-8"))
            return True
        except (InvalidSignature, ValueError):
            return False
    return hmac.compare_digest(hmac_hex(env("SPILVON_WALLET_SECRET"), s), headers.get("X-Spilvon-Signature", ""))


def is_for_us(body) -> bool:
    """After verifying, BEFORE moving money: the signed body must name YOU (operator_id is inside the
    signed bytes; the X-Spilvon-Operator header is not). One SPILVON Ed25519 key signs every casino's
    calls, so without this a call captured by another casino could be replayed here. HMAC and Ed25519."""
    return isinstance(body, dict) and body.get("operator_id") == env("SPILVON_OPERATOR")


# ---- amounts: integers in minor units --------------------------------------------------------
def to_minor(s, d: int) -> int:
    if not isinstance(s, str):
        raise ValueError("amount must be a string")
    v = Decimal(s)
    if v < 0 or v.as_tuple().exponent < -d:
        raise ValueError("bad amount")
    return int(v.scaleb(d))


def from_minor(v: int, d: int) -> str:
    return f"{v // 10**d}.{v % 10**d:0{d}d}" if d else str(v)


# ---- the wallet ------------------------------------------------------------------------------
lock = threading.Lock()  # PRODUCTION: a database transaction instead
balances, txs, tombstones, won_rounds = {}, {}, set(), set()
# Live casino sessions: token -> player. PRODUCTION: look the token up in your own session store.
# For the conformance run, set SPILVON_SAMPLE_TOKENS='{"<token>": "<player>"}'.
SESSIONS = json.loads(env("SPILVON_SAMPLE_TOKENS") or "{}")


def refuse(code, message=None):
    return {"error": {"code": code, **({"message": message} if message else {})}}


def handle(method: str, b: dict) -> dict:
    d = DECIMALS.get(b.get("currency"))
    if d is None or not isinstance(b.get("player_id"), str):
        return refuse("CURRENCY_MISMATCH")
    cur = b["currency"]

    def read(player):
        return balances.setdefault((player, cur), to_minor("1000", d))  # demo: new players start with 1000

    ok = lambda: {"balance": from_minor(read(b["player_id"]), d)}
    if method == "balance":
        return ok()
    amount = to_minor(b["amount"], d)
    ref = b.get("reference_transaction_id")
    details = {"type": method, "player": b["player_id"], "currency": cur, "amount": amount, "round": b.get("round_id"), "ref": ref}
    seen = txs.get(b["transaction_id"])
    if seen:  # 1. idempotency: identical repeat -> same answer; same id, other details -> refuse
        same = all(seen[k] == v for k, v in details.items())
        return ok() if same else refuse("TRANSACTION_MISMATCH", "transaction_id reused with different details")
    if method == "bet":
        if b["transaction_id"] in tombstones:
            return refuse("TRANSACTION_NOT_FOUND", "bet already cancelled")
        if SESSIONS.get(b.get("token")) != b["player_id"]:  # only bets check the token
            return refuse("TOKEN_INVALID")
        # your own checks: PLAYER_BLOCKED, LIMIT_REACHED, TOKEN_EXPIRED, GAME_NOT_ALLOWED
        if read(b["player_id"]) < amount:
            return refuse("INSUFFICIENT_FUNDS")
        balances[(b["player_id"], cur)] -= amount  # 2. all or nothing
    elif method == "win":
        read(b["player_id"])
        balances[(b["player_id"], cur)] += amount  # 4. always accepted; b.get("free_round") marks award wins
        won_rounds.add((b["player_id"], b.get("round_id")))
    elif method == "rollback":
        bet = txs.get(ref)
        if not bet or bet["type"] != "bet":
            tombstones.add(ref)  # 3. refuse that bet if it arrives late
            return refuse("TRANSACTION_NOT_FOUND")
        if (bet["player"], bet["currency"], bet["round"], bet["amount"]) != (b["player_id"], cur, b.get("round_id"), amount):
            return refuse("TRANSACTION_MISMATCH", "rollback does not match its bet")
        if (bet["player"], bet["round"]) in won_rounds:
            return refuse("ROUND_ALREADY_SETTLED", "the round already received its win")
        if not bet.get("rolled_back"):
            balances[(bet["player"], cur)] = read(bet["player"]) + bet["amount"]  # refund the bet's owner
            bet["rolled_back"] = True
    else:
        return refuse("INVALID_METHOD")
    txs[b["transaction_id"]] = details
    return ok()


class Wallet(BaseHTTPRequestHandler):
    def do_POST(self):
        raw = self.rfile.read(int(self.headers.get("Content-Length", 0))).decode("utf-8")
        method = self.path.split("?")[0].rstrip("/").split("/")[-1]
        if method not in ("balance", "bet", "win", "rollback"):
            return self.send(404, {"error": {"code": "NOT_FOUND"}})
        if not verify_spilvon(self.headers, "POST", self.path, raw):  # verify BEFORE parsing
            return self.send(401, {"error": {"code": "INVALID_SIGNATURE"}})
        try:
            body = json.loads(raw)
            if not is_for_us(body):  # AUD2-01: a call signed for another operator is a replay
                return self.send(401, {"error": {"code": "INVALID_SIGNATURE", "message": "operator_id is not ours"}})
            with lock:
                reply = handle(method, body)
        except (ValueError, KeyError):
            return self.send(400, {"error": {"code": "INVALID_REQUEST"}})
        self.send(200, reply)

    def send(self, status, obj):
        data = json.dumps(obj).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *args):
        pass


# ---- launch: one signed request ------------------------------------------------------------
def create_session(player_id: str, game_code: str, currency="USD", lang="en", token=None, mode="real") -> dict:
    path = "/api/v1/operator/sessions"
    body = json.dumps({"player_id": player_id, "game_code": game_code, "currency": currency, "lang": lang, "token": token, "mode": mode,
                       "lobby_url": "https://casino.example/lobby", "deposit_url": "https://casino.example/cashier"})
    ts = str(int(time.time() * 1000))
    req = urllib.request.Request(env("SPILVON_URL") + path, data=body.encode("utf-8"), method="POST", headers={
        "Content-Type": "application/json",
        "X-Spilvon-Operator": env("SPILVON_OPERATOR"),
        "X-Spilvon-Timestamp": ts,
        "X-Spilvon-Signature": hmac_hex(env("SPILVON_API_SECRET"), signing_string(ts, "POST", path, body)),
    })
    try:
        with urllib.request.urlopen(req, timeout=10) as res:
            return json.load(res)  # {session_id, player_id, launch_url, expires_in: 120}
    except urllib.error.HTTPError as e:
        err = json.load(e)
        raise RuntimeError(f"{err['error']['code']}: {err['error']['message']} (request_id {err.get('request_id')})")


if __name__ == "__main__":
    if sys.argv[1:2] == ["wallet"]:
        ThreadingHTTPServer(("", int(env("PORT") or 8080)), Wallet).serve_forever()
    elif sys.argv[1:2] == ["launch"]:
        print(create_session(sys.argv[2], sys.argv[3], token=f"casino-session-{sys.argv[2]}")["launch_url"])
