"""Tests for transaction building."""

from x402_stacks.stacks_tx.transaction import build_stx_transfer, build_contract_call
from x402_stacks.stacks_tx.clarity import (
    serialize_uint,
    serialize_standard_principal,
    serialize_optional_none,
)
from x402_stacks.stacks_tx.keys import private_key_to_address

TEST_KEY = "edf9aee84d9b7abc145504dde6726c64f369d37ee34ced614f76c2dcb7004497"


class TestBuildStxTransfer:
    def test_returns_hex_string(self):
        addr = private_key_to_address(TEST_KEY, "testnet")
        tx = build_stx_transfer(TEST_KEY, addr, 1000000, nonce=0, fee=200, network="testnet")
        assert isinstance(tx, str)
        # Valid hex
        bytes.fromhex(tx)

    def test_testnet_version(self):
        addr = private_key_to_address(TEST_KEY, "testnet")
        tx = build_stx_transfer(TEST_KEY, addr, 1000000, network="testnet")
        assert tx[:2] == "80"  # TX_VERSION_TESTNET

    def test_mainnet_version(self):
        addr = private_key_to_address(TEST_KEY, "mainnet")
        tx = build_stx_transfer(TEST_KEY, addr, 1000000, network="mainnet")
        assert tx[:2] == "00"  # TX_VERSION_MAINNET

    def test_with_memo(self):
        addr = private_key_to_address(TEST_KEY, "testnet")
        tx = build_stx_transfer(TEST_KEY, addr, 1000000, memo="test", network="testnet")
        assert isinstance(tx, str)
        bytes.fromhex(tx)

    def test_deterministic_with_same_params(self):
        addr = private_key_to_address(TEST_KEY, "testnet")
        tx1 = build_stx_transfer(TEST_KEY, addr, 1000000, nonce=5, fee=300, network="testnet")
        tx2 = build_stx_transfer(TEST_KEY, addr, 1000000, nonce=5, fee=300, network="testnet")
        assert tx1 == tx2


class TestBuildContractCall:
    def test_returns_hex_string(self):
        sender = private_key_to_address(TEST_KEY, "testnet")
        recipient = sender  # self-transfer for test
        fn_args = [
            serialize_uint(1000),
            serialize_standard_principal(sender),
            serialize_standard_principal(recipient),
            serialize_optional_none(),
        ]
        tx = build_contract_call(
            TEST_KEY,
            "ST1F7QA2MDF17S807EPA36TSS8AMEFY4KA9TVGWXT",
            "sbtc-token",
            "transfer",
            fn_args,
            nonce=0,
            fee=200,
            network="testnet",
        )
        assert isinstance(tx, str)
        bytes.fromhex(tx)

    def test_testnet_version(self):
        sender = private_key_to_address(TEST_KEY, "testnet")
        fn_args = [
            serialize_uint(1000),
            serialize_standard_principal(sender),
            serialize_standard_principal(sender),
            serialize_optional_none(),
        ]
        tx = build_contract_call(
            TEST_KEY,
            "ST1F7QA2MDF17S807EPA36TSS8AMEFY4KA9TVGWXT",
            "sbtc-token",
            "transfer",
            fn_args,
            network="testnet",
        )
        assert tx[:2] == "80"
