// SPILVON integration sample for Go 1.20+ (standard library only).
//
//	go run . wallet                  start the wallet API on :8080 (SPILVON calls it)
//	go run . 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.
package main

import (
	"bytes"
	"crypto/ed25519"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"math/big"
	"net/http"
	"os"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"
)

const skewMs = 300_000

var decimals = map[string]int{"USD": 2, "EUR": 2, "TRY": 2, "USDT": 6, "USDC": 6, "TRX": 6, "BTC": 8, "ETH": 8, "LTC": 8, "SOL": 8, "DOGE": 8}

func signingString(ts, method, pathAndQuery, body string) string {
	return ts + "." + strings.ToUpper(method) + "." + pathAndQuery + "." + body
}

func hmacHex(secret, s string) string {
	m := hmac.New(sha256.New, []byte(secret))
	m.Write([]byte(s))
	return hex.EncodeToString(m.Sum(nil))
}

// ---- verification of SPILVON's calls ------------------------------------------------------
var edKeys = func() map[string]ed25519.PublicKey {
	raw := map[string]string{}
	_ = json.Unmarshal([]byte(os.Getenv("SPILVON_ED25519_PUBLIC_KEYS")), &raw)
	out := map[string]ed25519.PublicKey{}
	for kid, b64 := range raw {
		if k, err := base64.StdEncoding.DecodeString(b64); err == nil && len(k) == ed25519.PublicKeySize {
			out[kid] = ed25519.PublicKey(k)
		}
	}
	return out
}()

var tsRe = regexp.MustCompile(`^\d{13}$`)

func verifySpilvon(h http.Header, method, pathAndQuery, rawBody string) bool {
	ts := h.Get("X-Spilvon-Timestamp")
	if h.Get("X-Spilvon-Operator") != os.Getenv("SPILVON_OPERATOR") || !tsRe.MatchString(ts) {
		return false
	}
	t, _ := strconv.ParseInt(ts, 10, 64)
	if d := time.Now().UnixMilli() - t; d > skewMs || d < -skewMs {
		return false
	}
	s := signingString(ts, method, pathAndQuery, rawBody)
	if edSig := h.Get("X-Spilvon-Signature-Ed25519"); edSig != "" && len(edKeys) > 0 {
		key, ok := edKeys[h.Get("X-Spilvon-Key-Id")] // unknown kid: refetch the key set once, then reject
		sig, err := base64.StdEncoding.DecodeString(edSig)
		return ok && err == nil && ed25519.Verify(key, []byte(s), sig)
	}
	return hmac.Equal([]byte(hmacHex(os.Getenv("SPILVON_WALLET_SECRET"), s)), []byte(h.Get("X-Spilvon-Signature")))
}

// ---- amounts: integers in minor units --------------------------------------------------------
func toMinor(s string, d int) (*big.Int, error) {
	if !regexp.MustCompile(fmt.Sprintf(`^\d+(\.\d{1,%d})?$`, d)).MatchString(s) {
		return nil, fmt.Errorf("bad amount")
	}
	whole, frac, _ := strings.Cut(s, ".")
	v, _ := new(big.Int).SetString(whole+frac+strings.Repeat("0", d-len(frac)), 10)
	return v, nil
}

func fromMinor(v *big.Int, d int) string {
	s := fmt.Sprintf("%0*s", d+1, v.String())
	return s[:len(s)-d] + "." + s[len(s)-d:]
}

// ---- the wallet ------------------------------------------------------------------------------
type tx struct {
	typ, player, currency, round, ref string
	amount                            *big.Int
	rolledBack                        bool
}

var (
	mu         sync.Mutex // PRODUCTION: a database transaction instead
	balances   = map[string]*big.Int{}
	txs        = map[string]*tx{}
	tombstones = map[string]bool{}
	wonRounds  = map[string]bool{} // player + ":" + round_id that received their win
	// Live casino sessions: token -> player. PRODUCTION: look the token up in your own session store.
	// For the conformance run: SPILVON_SAMPLE_TOKENS='{"<token>":"<player>"}'.
	sessions = func() map[string]string {
		m := map[string]string{}
		_ = json.Unmarshal([]byte(os.Getenv("SPILVON_SAMPLE_TOKENS")), &m)
		return m
	}()
)

type req struct {
	OperatorID    string  `json:"operator_id"`
	PlayerID      string  `json:"player_id"`
	Currency      string  `json:"currency"`
	Token         *string `json:"token"`
	TransactionID string  `json:"transaction_id"`
	RoundID       string  `json:"round_id"`
	Amount        string  `json:"amount"`
	RefID         *string `json:"reference_transaction_id"`
	FreeRound     bool    `json:"free_round"`
}

type errBody struct {
	Error struct {
		Code    string `json:"code"`
		Message string `json:"message,omitempty"`
	} `json:"error"`
}

func fail(code string) any { e := errBody{}; e.Error.Code = code; return e }

func handle(method string, b req) any {
	d, ok := decimals[b.Currency]
	if !ok || b.PlayerID == "" {
		return fail("CURRENCY_MISMATCH")
	}
	read := func(player string) *big.Int {
		k := player + ":" + b.Currency
		if balances[k] == nil {
			balances[k], _ = toMinor("1000", d) // demo: every new player starts with 1000
		}
		return balances[k]
	}
	okBody := func() any { return map[string]string{"balance": fromMinor(read(b.PlayerID), d)} }
	if method == "balance" {
		return okBody()
	}
	amount, err := toMinor(b.Amount, d)
	if err != nil {
		return fail("INVALID_REQUEST")
	}
	ref := ""
	if b.RefID != nil {
		ref = *b.RefID
	}
	if seen := txs[b.TransactionID]; seen != nil { // 1. idempotency
		if seen.typ == method && seen.player == b.PlayerID && seen.currency == b.Currency && seen.amount.Cmp(amount) == 0 && seen.round == b.RoundID && seen.ref == ref {
			return okBody()
		}
		return fail("TRANSACTION_MISMATCH") // same id, other details: not a retry
	}
	switch method {
	case "bet":
		if tombstones[b.TransactionID] {
			return fail("TRANSACTION_NOT_FOUND")
		}
		if b.Token == nil || sessions[*b.Token] != b.PlayerID { // only bets check the token
			return fail("TOKEN_INVALID")
		}
		// your own checks: PLAYER_BLOCKED, LIMIT_REACHED, TOKEN_EXPIRED, GAME_NOT_ALLOWED
		if read(b.PlayerID).Cmp(amount) < 0 {
			return fail("INSUFFICIENT_FUNDS")
		}
		read(b.PlayerID).Sub(read(b.PlayerID), amount) // 2. all or nothing
	case "win":
		read(b.PlayerID).Add(read(b.PlayerID), amount) // 4. always accepted; b.FreeRound marks award wins
		wonRounds[b.PlayerID+":"+b.RoundID] = true
	case "rollback":
		bet := txs[ref]
		if bet == nil || bet.typ != "bet" {
			tombstones[ref] = true // 3. refuse that bet if it arrives late
			return fail("TRANSACTION_NOT_FOUND")
		}
		if bet.player != b.PlayerID || bet.currency != b.Currency || bet.round != b.RoundID || bet.amount.Cmp(amount) != 0 {
			return fail("TRANSACTION_MISMATCH")
		}
		if wonRounds[bet.player+":"+bet.round] {
			return fail("ROUND_ALREADY_SETTLED")
		}
		if !bet.rolledBack {
			read(bet.player).Add(read(bet.player), bet.amount) // refund the bet's owner, from the stored bet
			bet.rolledBack = true
		}
	default:
		return fail("INVALID_METHOD")
	}
	txs[b.TransactionID] = &tx{typ: method, player: b.PlayerID, currency: b.Currency, round: b.RoundID, ref: ref, amount: amount}
	return okBody()
}

func walletHandler(w http.ResponseWriter, r *http.Request) {
	send := func(status int, v any) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(status)
		_ = json.NewEncoder(w).Encode(v)
	}
	parts := strings.Split(strings.TrimRight(r.URL.Path, "/"), "/")
	method := parts[len(parts)-1]
	if r.Method != http.MethodPost || !map[string]bool{"balance": true, "bet": true, "win": true, "rollback": true}[method] {
		send(404, fail("NOT_FOUND"))
		return
	}
	raw, _ := io.ReadAll(io.LimitReader(r.Body, 16<<10))
	if !verifySpilvon(r.Header, "POST", r.URL.RequestURI(), string(raw)) { // verify BEFORE parsing
		send(401, fail("INVALID_SIGNATURE"))
		return
	}
	var b req
	if err := json.Unmarshal(raw, &b); err != nil {
		send(400, fail("INVALID_REQUEST"))
		return
	}
	// 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 (AUD2-01).
	if b.OperatorID != os.Getenv("SPILVON_OPERATOR") {
		send(401, fail("INVALID_SIGNATURE"))
		return
	}
	mu.Lock()
	reply := handle(method, b)
	mu.Unlock()
	send(200, reply)
}

// ---- launch: one signed request ------------------------------------------------------------
func createSession(playerID, gameCode, currency string) (map[string]any, error) {
	path := "/api/v1/operator/sessions"
	body, _ := json.Marshal(map[string]any{"player_id": playerID, "game_code": gameCode, "currency": currency, "lang": "en",
		"token": "casino-session-" + playerID, "lobby_url": "https://casino.example/lobby", "deposit_url": "https://casino.example/cashier"})
	ts := strconv.FormatInt(time.Now().UnixMilli(), 10)
	rq, _ := http.NewRequest("POST", os.Getenv("SPILVON_URL")+path, bytes.NewReader(body))
	rq.Header.Set("Content-Type", "application/json")
	rq.Header.Set("X-Spilvon-Operator", os.Getenv("SPILVON_OPERATOR"))
	rq.Header.Set("X-Spilvon-Timestamp", ts)
	rq.Header.Set("X-Spilvon-Signature", hmacHex(os.Getenv("SPILVON_API_SECRET"), signingString(ts, "POST", path, string(body))))
	res, err := (&http.Client{Timeout: 10 * time.Second}).Do(rq)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	var out map[string]any
	_ = json.NewDecoder(res.Body).Decode(&out)
	if res.StatusCode != 201 {
		return nil, fmt.Errorf("launch failed: %v", out)
	}
	return out, nil // session_id, player_id, launch_url, expires_in (120)
}

func main() {
	if len(os.Args) > 1 && os.Args[1] == "wallet" {
		port := os.Getenv("PORT")
		if port == "" {
			port = "8080"
		}
		http.HandleFunc("/", walletHandler)
		_ = http.ListenAndServe(":"+port, nil)
	} else if len(os.Args) > 3 && os.Args[1] == "launch" {
		s, err := createSession(os.Args[2], os.Args[3], "USD")
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		fmt.Println(s["launch_url"])
	}
}
