import numpy as np

try:
    from numba import cuda, uint8, uint32, uint64
    HAS_CUDA = cuda.is_available()
except ImportError:
    HAS_CUDA = False

# Hardcoded cryptographic constants needed for device execution
K = np.array([
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
], dtype=np.uint32)

if HAS_CUDA:
    @cuda.jit(device=True, inline=True)
    def rotr(x, n):
        return uint32((x >> n) | (x << (32 - n)))
        
    @cuda.jit(device=True, inline=True)
    def ch(x, y, z): return uint32((x & y) ^ (~x & z))
    
    @cuda.jit(device=True, inline=True)
    def maj(x, y, z): return uint32((x & y) ^ (x & z) ^ (y & z))
    
    @cuda.jit(device=True, inline=True)
    def sigma0(x): return uint32(rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22))
    
    @cuda.jit(device=True, inline=True)
    def sigma1(x): return uint32(rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25))
    
    @cuda.jit(device=True, inline=True)
    def gamma0(x): return uint32(rotr(x, 7) ^ rotr(x, 18) ^ (x >> 3))
    
    @cuda.jit(device=True, inline=True)
    def gamma1(x): return uint32(rotr(x, 17) ^ rotr(x, 19) ^ (x >> 10))

    @cuda.jit(device=True)
    def sha256_transform(state, data, k_dev, w_glob, w_offset):
        for i in range(16):
            w_glob[w_offset + i] = uint32(data[i*4]) << 24 | uint32(data[i*4+1]) << 16 | \
                                   uint32(data[i*4+2]) << 8 | uint32(data[i*4+3])
        for i in range(16, 64):
            term1 = (gamma1(w_glob[w_offset + i-2]) + w_glob[w_offset + i-7]) & 0xFFFFFFFF
            term2 = (gamma0(w_glob[w_offset + i-15]) + w_glob[w_offset + i-16]) & 0xFFFFFFFF
            w_glob[w_offset + i] = uint32((term1 + term2) & 0xFFFFFFFF)
            
        a, b, c, d, e, f, g, h = state[0], state[1], state[2], state[3], state[4], state[5], state[6], state[7]
        for i in range(64):
            sum1 = (uint32(h) + sigma1(uint32(e))) & 0xFFFFFFFF
            sum2 = (ch(uint32(e), uint32(f), uint32(g)) + k_dev[i]) & 0xFFFFFFFF
            temp1 = (sum1 + sum2 + w_glob[w_offset + i]) & 0xFFFFFFFF
            sum3 = (sigma0(uint32(a)) + maj(uint32(a), uint32(b), uint32(c))) & 0xFFFFFFFF
            temp2 = sum3
            h = uint32(g)
            g = uint32(f)
            f = uint32(e)
            e = uint32((d + temp1) & 0xFFFFFFFF)
            d = uint32(c)
            c = uint32(b)
            b = uint32(a)
            a = uint32((temp1 + temp2) & 0xFFFFFFFF)
            
        state[0] = uint32((state[0] + a) & 0xFFFFFFFF)
        state[1] = uint32((state[1] + b) & 0xFFFFFFFF)
        state[2] = uint32((state[2] + c) & 0xFFFFFFFF)
        state[3] = uint32((state[3] + d) & 0xFFFFFFFF)
        state[4] = uint32((state[4] + e) & 0xFFFFFFFF)
        state[5] = uint32((state[5] + f) & 0xFFFFFFFF)
        state[6] = uint32((state[6] + g) & 0xFFFFFFFF)
        state[7] = uint32((state[7] + h) & 0xFFFFFFFF)

    @cuda.jit(device=True)
    def hmac_sha256_stake_check(server_seed_len, server_seed, client_seed_len, client_seed_msg, target_outcome, k_dev, w_glob, w_offset):
        block = cuda.local.array(64, uint8)
        for i in range(64):
            b = 0x36
            if i < server_seed_len:
                b ^= server_seed[i]
            block[i] = b
            
        state = cuda.local.array(8, uint32)
        state[0], state[1], state[2], state[3] = 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a
        state[4], state[5], state[6], state[7] = 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
        
        sha256_transform(state, block, k_dev, w_glob, w_offset)
        
        for i in range(64): block[i] = 0
        for i in range(client_seed_len): block[i] = client_seed_msg[i]
        block[client_seed_len] = 0x80
        
        msg_len_bits = (64 + client_seed_len) * 8
        block[62] = uint8(msg_len_bits >> 8)
        block[63] = uint8(msg_len_bits)
        
        sha256_transform(state, block, k_dev, w_glob, w_offset)
        
        inner_hash = cuda.local.array(32, uint8)
        for i in range(8):
            val = state[i]
            inner_hash[i*4] = uint8(val >> 24)
            inner_hash[i*4+1] = uint8(val >> 16)
            inner_hash[i*4+2] = uint8(val >> 8)
            inner_hash[i*4+3] = uint8(val)

        for i in range(64):
            b = 0x5c
            if i < server_seed_len:
                b ^= server_seed[i]
            block[i] = b
            
        state[0], state[1], state[2], state[3] = 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a
        state[4], state[5], state[6], state[7] = 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
        
        sha256_transform(state, block, k_dev, w_glob, w_offset)
        
        for i in range(64): block[i] = 0
        for i in range(32): block[i] = inner_hash[i]
        block[32] = 0x80
        block[62] = 0x03
        block[63] = 0x00
        
        sha256_transform(state, block, k_dev, w_glob, w_offset)
        
        val = state[0]
        if val < uint32(4294967296 / 10001 * 10000):
            roll = (val % 10000) / 100.0
            diff = roll - target_outcome
            if diff < 0: diff = -diff
            if diff < 0.001:
                return True
        return False

    @cuda.jit(device=True)
    def uint64_to_string(num, out_buffer):
        if num == 0:
            out_buffer[0] = 48
            return 1
        length = 0
        temp = num
        while temp > 0:
            length += 1
            temp //= 10
        for i in range(length):
            out_buffer[length - 1 - i] = 48 + (num % 10)
            num //= 10
        return length

    @cuda.jit
    def brute_force_kernel_beatstake(k_dev, client_msg_base_dev, client_msg_base_len, target_outcomes, num_targets, result_found, result_len, result_seed_idx, current_len, alphabet_dev, offset_idx, workspace_dev, prefix_dev, prefix_len, start_nonce):
        idx = cuda.grid(1)
        global_idx = idx + offset_idx
        
        if result_found[0] == 1:
            return
            
        w_offset = idx * 64
        test_seed = cuda.local.array(64, uint8)
        
        for i in range(prefix_len):
            test_seed[i] = prefix_dev[i]
            
        temp = global_idx
        for i in range(current_len):
            test_seed[prefix_len + current_len - 1 - i] = alphabet_dev[temp % 16]
            temp //= 16
            
        full_len = prefix_len + current_len
        msg_buffer = cuda.local.array(64, uint8)
        for i in range(client_msg_base_len):
            msg_buffer[i] = client_msg_base_dev[i]
            
        all_matched = True
        nonce_str_buf = cuda.local.array(20, uint8)
        for t_idx in range(num_targets):
            target = target_outcomes[t_idx]
            target_nonce = start_nonce + t_idx
            msg_len = client_msg_base_len
            nonce_len = uint64_to_string(target_nonce, nonce_str_buf)
            for i in range(nonce_len):
                msg_buffer[msg_len] = nonce_str_buf[i]
                msg_len += 1
                
            if not hmac_sha256_stake_check(full_len, test_seed, msg_len, msg_buffer, target, k_dev, workspace_dev, w_offset):
                all_matched = False
                break
                
        if all_matched:
            cuda.atomic.compare_and_swap(result_found, 0, 1)
            if result_found[0] == 1:
                result_len[0] = current_len
                result_seed_idx[0] = global_idx
