#   -*- coding: utf-8 -*-
#
#   This file is part of SKALE.py
#
#   Copyright (C) 2019-Present SKALE Labs
#
#   SKALE.py is free software: you can redistribute it and/or modify
#   it under the terms of the GNU Affero General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   SKALE.py is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU Affero General Public License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with SKALE.py.  If not, see <https://www.gnu.org/licenses/>.


import abc
import logging

import requests
from skale_contracts import skale_contracts
from skale_contracts.project_factory import SkaleProject
from web3 import Web3

from skale.rpc_session import CountingSession, RpcHttpStats
from skale.utils.cache import RedisCacheConfig
from skale.utils.exceptions import EmptyWalletError, InvalidWalletError
from skale.utils.helper import contract_name_to_snake_case
from skale.utils.web3_utils import default_gas_price, get_endpoint, init_web3
from skale.wallets import BaseWallet

logger = logging.getLogger(__name__)


class EmptyPrivateKey(Exception):
    pass


class SkaleBase:
    __metaclass__ = abc.ABCMeta

    DEFAULT_RPC_CACHE_TTL_POLICY: dict[str, int] = {
        'eth_call': 10,
        'eth_getCode': 30,
        'eth_getStorageAt': 30,
        'eth_chainId': 600,
        'eth_getBlockByNumber': 60,
        'eth_gasPrice': 5,
        'web3_clientVersion': 600,
    }

    def __init__(
        self,
        endpoint: str | list[str],
        alias_or_address: str,
        wallet: BaseWallet | None = None,
        state_path: str | None = None,
        ts_diff: int | None = None,
        provider_timeout: int = 30,
        session: requests.Session | None = None,
        enable_stats: bool = False,
        redis_cache_url: str | None = None,
        rpc_cache_methods: list[str] | None = None,
        rpc_cache_bypass_addresses: list[str] | None = None,
        rpc_cache_ttl_policy: dict[str, int] | None = None,
    ):
        logger.info(
            'Initializing %s, endpoint: %s, alias_or_address: %s, wallet: %s',
            self.__class__.__name__,
            endpoint,
            alias_or_address,
            type(wallet).__name__,
        )
        if state_path:
            logger.warning(
                'state_path is deprecated and will be ignored. This option will be removed in v8.'
            )
        self.stats = RpcHttpStats()
        if session is None and enable_stats:
            session = CountingSession(self.stats)
        self._endpoint = get_endpoint(endpoint, ts_diff=ts_diff, provider_timeout=provider_timeout)
        self._alias_or_address = alias_or_address

        cache_config = None
        if redis_cache_url is not None:
            cache_methods = rpc_cache_methods or [
                'eth_call',
                'eth_getCode',
                'eth_getStorageAt',
                'eth_chainId',
                'eth_getBlockByNumber',
                'eth_gasPrice',
                'web3_clientVersion',
            ]
            cache_ttl_policy = rpc_cache_ttl_policy or self.DEFAULT_RPC_CACHE_TTL_POLICY
            cache_config = RedisCacheConfig(
                redis_url=redis_cache_url,
                cache_methods=frozenset(cache_methods),
                bypass_addresses=frozenset(rpc_cache_bypass_addresses or []),
                default_ttl_seconds=0,
                method_ttl_policy=cache_ttl_policy,
            )
        self.web3 = init_web3(
            self._endpoint,
            ts_diff=ts_diff,
            provider_timeout=provider_timeout,
            session=session,
            cache_config=cache_config,
        )
        self.network = skale_contracts.get_network_by_provider(self.web3.provider)
        self.project = self.network.get_project(self.project_name)
        self.instance = self.project.get_instance(alias_or_address)
        if wallet:
            self.wallet = wallet

    @property
    @abc.abstractmethod
    def project_name(self) -> SkaleProject:
        """Name of smart contracts project"""

    @property
    def gas_price(self) -> int:
        return default_gas_price(self.web3)

    @property
    def wallet(self) -> BaseWallet:
        if not self._wallet:
            raise EmptyWalletError('No wallet provided')
        return self._wallet

    @wallet.setter
    def wallet(self, wallet: BaseWallet) -> None:
        if issubclass(type(wallet), BaseWallet):
            self._wallet = wallet
        else:
            raise InvalidWalletError(
                f'Wrong wallet class: {type(wallet).__name__}. \
                Must be one of the BaseWallet subclasses'
            )

    def _generate_legacy_abi(self) -> dict:
        abi = {}
        for contract_name in self.instance.abi.keys():
            if contract_name == 'RewardWallet':  # RewardWallet requires node id to get address
                continue
            address = Web3.to_checksum_address(self.instance.get_contract_address(contract_name))
            name = contract_name_to_snake_case(contract_name)
            abi[f'{name}_abi'] = self.instance.abi[contract_name]
            abi[f'{name}_address'] = address
        return abi
