"""Tool for buying merchant-specific verification credits with USDC, USDT, or BTC."""

import json
from typing import Any, Optional, Type

from langchain_core.callbacks import CallbackManagerForToolRun
from langchain_core.tools import BaseTool
from pydantic import BaseModel, Field

from langchain_insumer.wrapper import InsumerAPIWrapper


class BuyMerchantCreditsSchema(BaseModel):
    """Input for InsumerBuyMerchantCreditsTool."""

    id: str = Field(description="Merchant ID to buy credits for.")
    tx_hash: str = Field(description="Transaction hash proving payment.")
    chain_id: Any = Field(
        description=(
            "Payment chain: 1 (Ethereum), 8453 (Base), "
            '137 (Polygon), 42161 (Arbitrum), 10 (Optimism), 56 (BNB), '
            '43114 (Avalanche), "solana", or "bitcoin". '
            "USDC/USDT auto-detected on EVM and Solana. BTC converted to USD at market rate."
        ),
    )
    amount: Optional[float] = Field(
        default=None,
        description="Stablecoin amount sent. Minimum 5. Not required for BTC.",
    )
    update_wallet: bool = Field(
        default=False,
        description=(
            "When true, updates the registered wallet to the transaction "
            "sender. First purchase auto-registers the sender wallet. "
            "Subsequent purchases must match or include updateWallet=true."
        ),
    )


class InsumerBuyMerchantCreditsTool(BaseTool):
    """Buy verification credits for a specific merchant with USDC, USDT, or BTC. Owner only.

    Volume discounts: $5–$99 = 25 credits/$1 ($0.04/call), $100–$499 = 33/$1
    ($0.03/call), $500+ = 50/$1 ($0.02/call). Minimum $5.
    Merchant credits are separate from API key credits.
    USDC/USDT on EVM and Solana (auto-detected). BTC on Bitcoin (converted
    to USD at market rate). Non-refundable.
    """

    name: str = "insumer_buy_merchant_credits"
    description: str = (
        "Buy merchant verification credits by submitting a crypto transaction "
        "hash. Accepts USDC, USDT (auto-detected on EVM/Solana), or BTC (on "
        "Bitcoin, converted to USD at market rate). Volume discounts: $5–$99 = "
        "$0.04/call (25/$1), $100–$499 = $0.03 (33/$1), $500+ = $0.02 (50/$1). "
        "Owner only. Non-refundable."
    )
    args_schema: Type[BuyMerchantCreditsSchema] = BuyMerchantCreditsSchema

    api_wrapper: InsumerAPIWrapper = Field(..., exclude=True)

    def __init__(self, api_wrapper: InsumerAPIWrapper) -> None:
        super().__init__(api_wrapper=api_wrapper)

    def _run(
        self,
        id: str,
        tx_hash: str,
        chain_id: Any,
        amount: Optional[float] = None,
        update_wallet: bool = False,
        run_manager: Optional[CallbackManagerForToolRun] = None,
    ) -> str:
        """Buy merchant credits."""
        kwargs: dict[str, Any] = {
            "merchant_id": id,
            "tx_hash": tx_hash,
            "chain_id": chain_id,
            "update_wallet": update_wallet,
        }
        if amount is not None:
            kwargs["amount"] = amount
        result = self.api_wrapper.buy_merchant_credits(**kwargs)
        return json.dumps(result, indent=2)
