"""
Rewards are Txs with the claim-iscore method but since this service only listens for
new Txs, this job backfills the value and iscore from the logs service.
"""
import json

from requests import RequestException, get
from sqlmodel import func, select

from icon_governance.config import settings
from icon_governance.log import logger
from icon_governance.models.rewards import Reward
from icon_governance.utils.rpc import convert_hex_int


def get_iscore_value(tx_hash):
    """Get rewards value and Tx from logs service."""
    try:
        response = get(f"{settings.LOGS_SERVICE_URL}/api/v1/logs?transaction_hash={tx_hash}")
    except RequestException as e:
        logger.info(f"Exception in iscore - \n{e} - \n{tx_hash}")
        return None, None

    if response.status_code == 200:
        try:
            data = json.loads(response.json()[0]["data"])
            return convert_hex_int(data[0]) / 1e18, convert_hex_int(data[1]) / 1e18
        except Exception as e:
            logger.info(f"Exception in iscore - \n{e} - \n{tx_hash}")
            return None, None
    else:
        logger.info(f"Could not find Tx hash from logs service {tx_hash}")


def get_rewards(session):
    """
    Cron to get all the values and iscores for rewards txs. Works by getting all the
    iscore distributions which are picked up by the transactions processor and insert
    them into a DB. The values are then inserted with this cron job by querying for
    rewards that have no value.
    """
    count = (
        session.execute(select([func.count(Reward.address)]).where(Reward.value == None))
        .scalars()
        .all()
    )

    logger.info(f"Found {count} number of rewards records.")

    chunk_size = 10
    for i in range(0, int(count[0] / chunk_size) + 1):
        rewards = (
            session.execute(select(Reward).where(Reward.value == None).limit(chunk_size))
            .scalars()
            .all()
        )
        for r in rewards:
            # Get value from logs service
            iscore, value = get_iscore_value(tx_hash=r.tx_hash)

            if iscore is None:
                continue

            r.value = value
            r.iscore = iscore

            session.add(r)
            try:
                session.commit()
            except:
                session.rollback()
                raise

requests.get sqlmodel.func.count icon_governance.log.logger.info sqlmodel.select icon_governance.utils.rpc.convert_hex_int
[((1647, 1703), 'icon_governance.log.logger.info', 'logger.info', (['f"""Found {count} number of rewards records."""'], {}), "(f'Found {count} number of rewards records.')\n", (1658, 1703), False, 'from icon_governance.log import logger\n'), ((558, 632), 'requests.get', 'get', (['f"""{settings.LOGS_SERVICE_URL}/api/v1/logs?transaction_hash={tx_hash}"""'], {}), "(f'{settings.LOGS_SERVICE_URL}/api/v1/logs?transaction_hash={tx_hash}')\n", (561, 632), False, 'from requests import RequestException, get\n'), ((1100, 1166), 'icon_governance.log.logger.info', 'logger.info', (['f"""Could not find Tx hash from logs service {tx_hash}"""'], {}), "(f'Could not find Tx hash from logs service {tx_hash}')\n", (1111, 1166), False, 'from icon_governance.log import logger\n'), ((675, 734), 'icon_governance.log.logger.info', 'logger.info', (['f"""Exception in iscore - \n{e} - \n{tx_hash}"""'], {}), '(f"""Exception in iscore - \n{e} - \n{tx_hash}""")\n', (686, 734), False, 'from icon_governance.log import logger\n'), ((994, 1053), 'icon_governance.log.logger.info', 'logger.info', (['f"""Exception in iscore - \n{e} - \n{tx_hash}"""'], {}), '(f"""Exception in iscore - \n{e} - \n{tx_hash}""")\n', (1005, 1053), False, 'from icon_governance.log import logger\n'), ((886, 910), 'icon_governance.utils.rpc.convert_hex_int', 'convert_hex_int', (['data[0]'], {}), '(data[0])\n', (901, 910), False, 'from icon_governance.utils.rpc import convert_hex_int\n'), ((919, 943), 'icon_governance.utils.rpc.convert_hex_int', 'convert_hex_int', (['data[1]'], {}), '(data[1])\n', (934, 943), False, 'from icon_governance.utils.rpc import convert_hex_int\n'), ((1544, 1570), 'sqlmodel.func.count', 'func.count', (['Reward.address'], {}), '(Reward.address)\n', (1554, 1570), False, 'from sqlmodel import func, select\n'), ((1828, 1842), 'sqlmodel.select', 'select', (['Reward'], {}), '(Reward)\n', (1834, 1842), False, 'from sqlmodel import func, select\n')]