from app.main import main
from app.main.utils.common import response_message, read_data, read_rules, write_validations
from app.rulemall import RulesGroup
import pandas as pd


@main.route('/validate/<dsid>/<rgid>', methods=['GET', 'POST'])
def validate(dsid, rgid):
    configs = read_rules(rgid, where='db')
    print('got rules')
    rg = RulesGroup(rules=[])
    rg.from_dict(configs)
    # cols = rg.get_target()
    data = read_data(dsid)
    print('got data')
    rg.reset_data(data)
    data['loan_balance'] = data['loan_balance'].round(0).astype(pd.Int64Dtype())
    validation, responsible = rg.validate()
    validation.name = 'validated'
    print('validated')
    # .rename(columns={'customer_id': 'شناسه مشتری', 'loan_id': 'شناسه تسهیلات', 'loan_balance': 'مبلغ تسهیلات'})
    index_cols = data[['customer_id', 'loan_id', 'loan_balance']]
    validation = pd.concat([index_cols, validation, responsible], axis=1).iloc[:, 1:]
    validation = validation.reset_index().rename(columns={'index': 'rid'})
    # TODO return rule group id

    # validation['rgid'] = rgid
    # validation['dsid'] = dsid
    # result = write_validations(validation, where='db')
    # return response_message(result)
    return response_message(validation.to_dict(orient='records'))
