from time import sleep

from sqlmodel import select

from icon_governance.config import settings
from icon_governance.log import logger
from icon_governance.metrics import prom_metrics
from icon_governance.models.preps import Prep
from icon_governance.utils.rpc import convert_hex_int, getStake, post_rpc_json


def get_prep_stake(session):
    result = session.execute(select(Prep))
    preps = result.scalars().all()

    for prep in preps:
        prep.stake = convert_hex_int(post_rpc_json(getStake(prep.address))["stake"]) / 1e18

        session.merge(prep)
        session.commit()


def prep_stake_cron(session):
    while True:
        logger.info("Starting stake cron")
        get_prep_stake(session)
        logger.info("Prep stake ran.")
        prom_metrics.preps_stake_cron_ran.inc()
        sleep(settings.CRON_SLEEP_SEC)


if __name__ == "__main__":
    from icon_governance.db import session_factory

    get_prep_stake(session_factory())

icon_governance.metrics.prom_metrics.preps_stake_cron_ran.inc icon_governance.utils.rpc.getStake icon_governance.db.session_factory time.sleep icon_governance.log.logger.info sqlmodel.select
[((370, 382), 'sqlmodel.select', 'select', (['Prep'], {}), '(Prep)\n', (376, 382), False, 'from sqlmodel import select\n'), ((645, 679), 'icon_governance.log.logger.info', 'logger.info', (['"""Starting stake cron"""'], {}), "('Starting stake cron')\n", (656, 679), False, 'from icon_governance.log import logger\n'), ((720, 750), 'icon_governance.log.logger.info', 'logger.info', (['"""Prep stake ran."""'], {}), "('Prep stake ran.')\n", (731, 750), False, 'from icon_governance.log import logger\n'), ((759, 798), 'icon_governance.metrics.prom_metrics.preps_stake_cron_ran.inc', 'prom_metrics.preps_stake_cron_ran.inc', ([], {}), '()\n', (796, 798), False, 'from icon_governance.metrics import prom_metrics\n'), ((807, 837), 'time.sleep', 'sleep', (['settings.CRON_SLEEP_SEC'], {}), '(settings.CRON_SLEEP_SEC)\n', (812, 837), False, 'from time import sleep\n'), ((938, 955), 'icon_governance.db.session_factory', 'session_factory', ([], {}), '()\n', (953, 955), False, 'from icon_governance.db import session_factory\n'), ((494, 516), 'icon_governance.utils.rpc.getStake', 'getStake', (['prep.address'], {}), '(prep.address)\n', (502, 516), False, 'from icon_governance.utils.rpc import convert_hex_int, getStake, post_rpc_json\n')]