"""High-level transaction builders for Stacks.

Provides build_stx_transfer() and build_contract_call() which handle
all serialization details and return the signed transaction as a hex string.
"""

from __future__ import annotations

from .constants import (
    TX_VERSION_MAINNET,
    TX_VERSION_TESTNET,
    CHAIN_ID_MAINNET,
    CHAIN_ID_TESTNET,
    AUTH_TYPE_STANDARD,
    ANCHOR_MODE_ANY,
    POST_CONDITION_MODE_ALLOW,
)
from .payloads import serialize_token_transfer_payload, serialize_contract_call_payload
from .authorization import sign_transaction


def _get_tx_params(network: str) -> tuple[int, int]:
    """Return (version, chain_id) for the given network."""
    if network == "mainnet":
        return TX_VERSION_MAINNET, CHAIN_ID_MAINNET
    return TX_VERSION_TESTNET, CHAIN_ID_TESTNET


def _empty_post_conditions() -> bytes:
    """Return serialized empty post-conditions list (4-byte zero count)."""
    return (0).to_bytes(4, "big")


def build_stx_transfer(
    private_key: str,
    recipient: str,
    amount: int,
    *,
    memo: str = "",
    nonce: int = 0,
    fee: int = 200,
    network: str = "testnet",
) -> str:
    """Build a signed STX token transfer transaction.

    Returns the hex-encoded signed transaction.
    """
    version, chain_id = _get_tx_params(network)
    payload = serialize_token_transfer_payload(recipient, amount, memo)
    post_conditions = _empty_post_conditions()

    tx_bytes = sign_transaction(
        private_key,
        version=version,
        chain_id=chain_id,
        auth_type=AUTH_TYPE_STANDARD,
        nonce=nonce,
        fee=fee,
        anchor_mode=ANCHOR_MODE_ANY,
        post_condition_mode=POST_CONDITION_MODE_ALLOW,
        post_conditions=post_conditions,
        payload=payload,
    )
    return tx_bytes.hex()


def build_contract_call(
    private_key: str,
    contract_address: str,
    contract_name: str,
    function_name: str,
    function_args: list[bytes],
    *,
    nonce: int = 0,
    fee: int = 200,
    network: str = "testnet",
) -> str:
    """Build a signed contract call transaction.

    Returns the hex-encoded signed transaction.
    """
    version, chain_id = _get_tx_params(network)
    payload = serialize_contract_call_payload(
        contract_address, contract_name, function_name, function_args,
    )
    post_conditions = _empty_post_conditions()

    tx_bytes = sign_transaction(
        private_key,
        version=version,
        chain_id=chain_id,
        auth_type=AUTH_TYPE_STANDARD,
        nonce=nonce,
        fee=fee,
        anchor_mode=ANCHOR_MODE_ANY,
        post_condition_mode=POST_CONDITION_MODE_ALLOW,
        post_conditions=post_conditions,
        payload=payload,
    )
    return tx_bytes.hex()
