"""TradeRawModule — low-level trade execution with raw calldata.

For advanced users who want to construct their own adapter calldata and
route it through the TradeRouter directly.
"""

from __future__ import annotations

from openhedge.models.trade import TradeResult, TradeType
from openhedge.modules.base import BaseModule


class TradeRawModule(BaseModule):
    """Execute arbitrary adapter calls through the TradeRouter."""

    async def execute_raw(
        self,
        vault: str,
        adapter: str,
        data: bytes | str,
    ) -> TradeResult:
        """Route pre-encoded calldata to an adapter.

        Parameters
        ----------
        vault:
            Vault address that the adapter will act on behalf of.
        adapter:
            Target adapter contract address.
        data:
            ABI-encoded adapter calldata (hex string or bytes).
        """
        if isinstance(data, str):
            raw_data = bytes.fromhex(data[2:]) if data.startswith("0x") else bytes.fromhex(data)
        else:
            raw_data = data

        calldata = self._encode_call(
            "route(address,address,bytes)",
            ["address", "address", "bytes"],
            [vault, adapter, raw_data],
        )

        trade_router = self._contracts["trade_router"]
        receipt = await self._send_tx(to=trade_router, data=calldata)

        return TradeResult(
            tx_hash=receipt.get("transactionHash", ""),
            trade_type=TradeType.RAW,
            block_number=int(receipt.get("blockNumber", "0x0"), 16),
            gas_used=int(receipt.get("gasUsed", "0x0"), 16),
            status=int(receipt.get("status", "0x1"), 16),
            adapter=adapter,
            vault=vault,
        )
