#!/usr/bin/env python3
# Someone's FSInf-coin utils.
#   Copyright (c) 2021 by Someone <someone@somenet.org> (aka. Jan Vales <jan@jvales.net>)
#   published under MIT-License
#
# Run as cronjob:
#   40 * * * * (cd ~/gitstuff/neo-infcoin-utils/vowi_awards; ./infcoin_process_changes.py) &> /tmp/infcoin_process_changes.py.log
#
# awards infcoins to vowi-contributions.
#


import json
import os
import pprint
import signal
import requests

import mwclient


import config


def process_recent_mw_changes(mws):
    try:
        with open('data/infcoin_process_changes-'+mws.host+'.json') as file_handle:
            changes = json.load(file_handle)
    except:
        changes = dict()
    if 'delme' in changes:
        del changes['delme']

    if 'revid' not in changes:
        changes['revid'] = 138500

    if 'infcoin_addr' not in changes:
        changes['infcoin_addr'] = dict()

    max_revid = mws.recentchanges().next()['revid']
    print("revid:"+str(changes['revid'])+", max_revid:"+str(max_revid))

    # Iterate over all revisions since the last run and find wallet addresses.
    for i in range(changes['revid'], max_revid):
        revision = mws.revisions([i])
        if not revision:
            continue
        revision = revision[0]
        changes['revid'] = revision['revid']

        if len(revision['comment'].strip()) < 34 or "minor" in revision or "bot" in revision:
            continue

        infcoin_addr = revision['comment'].strip().split()
        infcoin_addr = infcoin_addr[len(infcoin_addr)-1]
        if not (len(infcoin_addr) == 34 and infcoin_addr.isalnum() and infcoin_addr.isascii()):
            continue

        if infcoin_addr in changes['infcoin_addr']:
            changes['infcoin_addr'][infcoin_addr].add(revision['revid'])
        else:
            changes['infcoin_addr'][infcoin_addr] = set([revision['revid']])


    # request coins for all changes
    for addr,revs in changes['infcoin_addr'].copy().items():
        print("processing:"+addr)
        for rev in revs:
            requests.get(config.infcoin_req_url, {"auth_name":config.infcoin_req_user, "auth_secret":config.infcoin_req_pw, "addr":addr, "amount":config.infcoin_req_amount, "reason_uniq":"wiki-"+mws.host+", revid="+str(rev)})

        del changes['infcoin_addr'][addr]
        with open('data/infcoin_process_changes-'+mws.host+'.json', 'w') as file_handle:
            json.dump(changes, file_handle)


    # warn if not all were processed.
    if len(changes['infcoin_addr']) != 0:
        print('Some requests failed!')
        pprint.pprint(changes)



if __name__ == '__main__':
    def signal_handler(signal, frame):
        print('SIG received. exitting!')
        os._exit(0)
    signal.signal(signal.SIGINT, signal_handler)

    mws = mwclient.Site(config.mw_name, path='/', retry_timeout=120)
    mws.login(config.mw_user, config.mw_user_pw)

    process_recent_mw_changes(mws)
