import hashlib
import time
import random

class Block:
    def __init__(self, block_number, transactions, previous_hash, timestamp, nonce, reward):
        self.block_number = block_number
        self.transactions = transactions
        self.previous_hash = previous_hash
        self.timestamp = timestamp
        self.nonce = nonce
        self.reward = reward
        self.hash = self.calculate_hash()

    def calculate_hash(self):
        data = str(self.block_number) + str(self.transactions) + self.previous_hash + str(self.timestamp) + str(self.nonce) + str(self.reward)
        return hashlib.sha256(data.encode()).hexdigest()

def mine_block(block_number, transactions, previous_hash, earnings_accounts):
    difficulty = 4  # Number of leading zeros required in the hash
    prefix = '0' * difficulty
    timestamp = int(time.time())
    nonce = 0

    # Generate a random reward within the range of $160 to $200
    reward = round(random.uniform(160, 200), 2)

    # Add the earnings transaction to the transactions list
    earnings_tx = f"Monero earnings: ${reward:.2f} to {earnings_accounts}"
    transactions.append(earnings_tx)

    while True:
        data = str(block_number) + str(transactions) + previous_hash + str(timestamp) + str(nonce) + str(reward)
        hash_result = hashlib.sha256(data.encode()).hexdigest()
        if hash_result.startswith(prefix):
            return Block(block_number, transactions, previous_hash, timestamp, nonce, reward)
        nonce += 1

if __name__ == "__main__":
    # Example usage to mine a block and distribute earnings
    block_number = 1
    previous_hash = "Previous block's hash goes here..."  # Set this to the hash of the previous block
    earnings_accounts = "Apple Wallet"  # Choose between "Apple Wallet" or "PayPal"

    # Define the transactions list
    transactions = []

    start_time = time.time()
    mined_block = mine_block(block_number, transactions, previous_hash, earnings_accounts)
    end_time = time.time()
    elapsed_time = end_time - start_time

    print("Block mined successfully!")
    print(f"Block Number: {mined_block.block_number}")
    print("Transactions:")
    for tx in mined_block.transactions:
        print(f"  - {tx}")
    print(f"Previous Hash: {mined_block.previous_hash}")  # This will display the hash of the previous block
    print(f"Timestamp: {mined_block.timestamp}")
    print(f"Nonce: {mined_block.nonce}")
    print(f"Reward: ${mined_block.reward:.2f}")  # Display the mining reward for this block
    print(f"Hash: {mined_block.hash}")
    print(f"Time taken: {elapsed_time:.2f} seconds")