"""zg_storage.contracts.market_contract module."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any, Optional

from web3 import Web3

from ..evm import EvmClient


class MarketContractClient:
    """MarketContractClient class.

    Purpose:
        Wrapper for the Market contract to query pricing."""

    def __init__(self, evm: EvmClient, address: str, abi_path: Optional[str] = None) -> None:
        self.evm = evm
        self.address = Web3.to_checksum_address(address)
        abi = self._load_abi(abi_path)
        self.contract = self.evm.w3.eth.contract(address=self.address, abi=abi)

    @staticmethod
    def _load_abi(abi_path: Optional[str]) -> Any:
        """Load the Market contract ABI from a path or default location."""
        if abi_path is None:
            here = Path(__file__).resolve()
            abi_path = here.parent.parent / "storage-contracts-abis" / "FixedPrice.json"
        else:
            abi_path = Path(abi_path)
        data = json.loads(abi_path.read_text())
        return data.get("abi", data)

    def price_per_sector(self) -> int:
        return int(self.contract.functions.pricePerSector().call())
